Friday, January 24, 2014

Binary Tree Level Order Traversal LeetCode

这个题思路很简单,利用一个Queue来存所有的node,然后利用两个counter来存当前层的元素个数,和下一层的元素个数。
BFS 现在BFS写的越来越熟练了,DFS还是不够熟练。


public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null) return result;

Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);

int currentElement = 1;

while (q.size() != 0 ){
int nextElement = 0;
ArrayList<Integer> currentLevel = new ArrayList<Integer>();
//check every node in the current level
for (int i = 0; i < currentElement; i++){
TreeNode curr = q.poll();
currentLevel.add(curr.val);
//check the left and right of the current node
//If it's not null, we add the node in the queue and update the nextElement
if (curr.left != null) {
q.add(curr.left);
nextElement++;
}
if (curr.right != null) {
q.add(curr.right);
nextElement++;
}
}
result.add(currentLevel);
currentElement = nextElement;
}
return result;
    }

No comments:

Post a Comment