天天看點

Leetcode102. 二叉樹的層次周遊

給定一個二叉樹,傳回其按層次周遊的節點值。 (即逐層地,從左到右通路所有節點)。

例如:

給定二叉樹: 

[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>> res=new LinkedList<List<Integer>>();
        if(root==null){
            return  res;
        }
        ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size=queue.size();
            List<Integer> list=new LinkedList<Integer>();
            while(size>0){
                TreeNode tmp=queue.removeFirst();
                list.add(tmp.val);
                if(tmp.left!=null){
                    queue.addLast(tmp.left);
                }
                if(tmp.right!=null){
                    queue.add(tmp.right);
                }
                size--;
            }
            res.add(list);
        }
        return res;
    }
}