[Leetcode]-- Binary Tree Level Order Traversal

[解题思路]

1.可以维护两个queue,当前层一个,下一层一个

2.记录下一层元素个数,这样每次遍历时就知道何时结束,只需一个queue

 

这题就是BFS,不论是图还是树的一种基本遍历的方法,应该掌握,比较简单,我用了2个queue来存,其实不需要,用一个count来计数每一层的node的个数,我使用了一个queue在level order traversal ii里面

 

 

[Leetcode]-- Binary Tree Level Order Traversal
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        if(root == null)
            return result;
            
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        //用来计数每一层有多少个Node
        int nextLevelCount = 1;
        
        while(!queue.isEmpty()){
            int curLevel = nextLevelCount;
            nextLevelCount = 0;
            ArrayList<Integer> lvl = new ArrayList<Integer>();
            // 此循环就是根据nextLevelCount来从队列里拿出多少个Node
            for(int i = 0; i < curLevel; i++){
                TreeNode tmp = queue.poll();
                lvl.add(tmp.val);
                if(tmp.left != null){
                    queue.add(tmp.left);
                    nextLevelCount++;
                }
                if(tmp.right != null){
                    queue.add(tmp.right);
                    nextLevelCount++;
                }
            }
            result.add(lvl);
        }
        return result;
    }
}
[Leetcode]-- Binary Tree Level Order Traversal

 

 

 

 

ref:http://www.cnblogs.com/feiling/p/3258537.html

[Leetcode]-- Binary Tree Level Order Traversal

上一篇:[Leetcode]-- Sum Root to Leaf Numbers


下一篇:小花猫的故事