Junhc

岂止于博客

LeetCode之二叉树的层次遍历

102. 二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
代码实现
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public List<List<Integer>> levelOrder(TreeNode root) {
   List<List<Integer>> orderList = new ArrayList<>();
   if(root == null) return orderList;
   List<TreeNode> nodeList = new ArrayList<>();
   nodeList.add(root);
   while(nodeList.size() > 0){
       List<TreeNode> childNodeList = new ArrayList<>();
       List<Integer> list = new ArrayList<>();
       for(int i =0; i<nodeList.size(); i++){
           TreeNode node = nodeList.get(i);
           if(node != null){
               list.add(node.val);
               if(node.left != null){
                   childNodeList.add(node.left);
               }
               if(node.right != null){
                   childNodeList.add(node.right);
               }
           }
       }
       orderList.add(list);
       nodeList = childNodeList;
   }
   return orderList;
}