103. Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

Solution1:BFS

思路: BFS + 交替每行cur_result 添加到头/尾
Time Complexity: O(N) Space Complexity: O(N)

Solution2:pre-order DFS with level

思路:DFS过程中不同level的结果list 保存到 对应ArrayList result[level]中
Time Complexity: O(N) Space Complexity: O(N) 递归缓存

Solution1 Code:

class Solution1 {
    public List> zigzagLevelOrder(TreeNode root) {
        Queue queue = new LinkedList();
        List> result = new LinkedList>();
        
        if(root == null) return result;
        
        boolean order = true;
        queue.offer(root);
        while(!queue.isEmpty()) {
            int num_on_level = queue.size();
            List cur_result = new LinkedList();
            for(int i = 0; i < num_on_level; i++) {
                TreeNode cur = queue.poll();
                if(cur.left != null) queue.add(cur.left);
                if(cur.right != null) queue.add(cur.right);
                
                // add result to cur_result
                if(order) cur_result.add(cur.val);
                else cur_result.add(0, cur.val);   
            }
            result.add(cur_result);
            order = order ? false : true;
        }
        return result;
    }
}

Solution2 Code:

class Solution2 {
    public List> zigzagLevelOrder(TreeNode root) {
        List> result = new ArrayList>();
        dfs(result, root, 0);
        return result;
    }
    
    public void dfs(List> result, TreeNode root, int level) {
        if (root == null) return;
        if (level == result.size()) {
            result.add(new LinkedList());
        }
        List list = result.get(level);
        if(level % 2 == 0) list.add(root.val);
        else list.add(0, root.val);
           
        dfs(result, root.left, level + 1);
        dfs(result, root.right, level + 1);
    }
}

你可能感兴趣的:(103. Binary Tree Zigzag Level Order Traversal)