1. 程式人生 > >[Leetcode] 102. 二叉樹的層次遍歷 java

[Leetcode] 102. 二叉樹的層次遍歷 java

和107類似,區別是不需要向結果中倒插list

給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。

例如:
給定二叉樹: [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; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result=new ArrayList();
        List<TreeNode> list=new ArrayList();
        if(root==null) return result;
        list.add(root);
        while(!list.isEmpty()){
            List<Integer> curList=new ArrayList();
            List<TreeNode> nextList=new ArrayList();
            for(TreeNode cur:list){
                curList.add(cur.val);
                if(cur.left!=null) nextList.add(cur.left);
                if(cur.right!=null) nextList.add(cur.right);
            }
            list=nextList;
            result.add(curList);
        }
        return result;
    }
}