[leet code] Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:我知女人心大雷小雷 编辑:程序博客网 时间:2024/05/23 01:46

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,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its zigzag level order traversal as:

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

================

Idea is base on the binary tree level order transverse.  The change for this problem is that when we are adding node for level%2 ==0, we need to add node from left to right.  Otherwise, we need to add node from right to left.

To implement this change, I firstly try to reverse the adding order by changing the order of recursive call, i.e. when current level%2 == 0, process its right child then left child.  However, the result turned out that it's wrong.  for example, in the case of {3,9,20,1,2,15,7} the output of 2nd level would be [15,7,1,2], while we are expecting [1,2,15,7].  In another word, this approach can only "partially" implement the order reverse.

Another way of reversing the order is when we are constructing the array list for current level, we can choose to add at the beginning of the array list, or in at the end of the array list.  In this case, we always process child nodes from left to right, we control the order of the all nodes in specific level by controlling the adding position (at the beginning or at the end).

/** * 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>> zigzagLevelOrder(TreeNode root) {        ArrayList<ArrayList<Integer>> rs = new ArrayList<ArrayList<Integer>>();        if(root == null) return rs;        helper(root, 0, rs);        return rs;    }        public void helper(TreeNode node, int depth, ArrayList<ArrayList<Integer>> rs){        if(node == null) return;                ArrayList<Integer> currLevel = null;        if(rs.size()<depth+1){            currLevel = new ArrayList<Integer>();            rs.add(currLevel);        }        else currLevel=rs.get(depth);                if(depth%2==0) currLevel.add(node.val);// newly added for this problem        else currLevel.add(0, node.val);// newly added for this problem                helper(node.left, depth+1, rs);        helper(node.right, depth+1, rs);    }}


0 0