1. 程式人生 > >102,二叉樹的層次遍歷

102,二叉樹的層次遍歷

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

例如:
給定二叉樹: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其層次遍歷結果:

[
  [3],
  [9,20],
  [15,7]
]

解答:

1.對於不為空的結點,先把該結點加入到佇列中

2.從隊中拿出結點,如果該結點的左右結點不為空,就分別把左右結點加入到佇列中

3.重複以上操作直到佇列為空

/**
 * 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>> bb=new ArrayList<List<Integer>>();       
        LinkedList<TreeNode> queue =new LinkedList<TreeNode>();
         TreeNode root1;
        if (root == null) return bb;
     
        queue.add(root);
        
        while (!queue.isEmpty()) {            
            List<Integer> aa=new ArrayList<Integer>();
            int a=queue.size();
            for (int i=0;i<a;i++)
            {
                 root1 = queue.poll();
               
                // printf("%c ", root -> data);
                 aa.add(root1.val);
                if (root1.left!=null)
                {
                      queue.add(root1.left);
                }
                
                if (root1.right!=null)
                {
                     queue.add(root1.right);
                }
                   
                
            }
            bb.add(aa);
        }
        return bb;
    }
}