lintcode : 二叉樹的層次遍歷


題目

二叉樹的層次遍歷

給出一棵二叉樹,返回其節點值的層次遍歷(逐層從左往右訪問)

樣例

給一棵二叉樹 {3,9,20,#,#,15,7} :

  3
 / \
9  20
  /  \
 15   7

返回他的分層遍歷結果:

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

挑戰1:只使用一個隊列去實現它

挑戰2:用DFS算法來做

解題 


隊列很容易,先加入,然后取出來的同時加入左右孩子節點

在劍指offer中有個題目和這個很類似,其只是層次遍歷二叉樹,沒有要求把每層的節點單獨放在一起的。

上面說的規律:每一次打印一個節點的時候,如果該結點有子結點,則把該結點的子結點放到一個隊列的尾部。接下來到隊列的頭部取出最早進入隊列的結點。

重復前面的打印操作,直到隊列中所有的結點都被打印出來為止。

上面是層次打印所有節點,而不是對每一層的節點放在一個list中輸出,所以隊列保存當前層的元素。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        // write your code here
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
        if(root == null)
            return tree;
        queue.offer(root);
        while(!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<Integer>();
            int size = queue.size();
            for(int i=0;i<size;i++){
                TreeNode head = queue.poll();
                list.add(head.val);
                if(head.left!=null){
                    queue.offer(head.left);
                }
                if(head.right!=null){
                    queue.offer(head.right);
                }
            }
            tree.add(list);
        }
        return tree;
    }
}
Java Code

 DFS程序,參見九章


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM