[LintCode/LeetCode] Binary Tree Level Order Traversal I & II

295 查看

Problem

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

Note

本来用stack和两个while循环做的,用curStack在内部循环,先右后左增加下层结点后替换外部的stack。然而没有AC,就换了先入先出的Queue。用size标记每一层的结点数目并定向循环。

Solution

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList();
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> temp = new ArrayList();
            for(int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                temp.add(cur.val);
                if (cur.left != null) queue.add(cur.left);
                if (cur.right != null) queue.add(cur.right);
            }
            res.add(temp); //for traversal II: res.add(0, temp);
        }
        return res;
    }
}

DFS

public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        helper(root, res, 0);
        return res;
    }
    public void helper(TreeNode root, ArrayList<ArrayList<Integer>> res, int index) {
        int size = res.size();
        if (index == size) {
            ArrayList<Integer> curList = new ArrayList<>();
            curList.add(root.val);
            res.add(0, curList);
        }
        else res.get(size-index-1).add(root.val);
        if (root.left != null) helper(root.left, res, index+1);
        if (root.right != null) helper(root.right, res, index+1);
    }
}