Binary Tree Zigzag Level Order Traversal, Leetcode 解题笔记

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]
]

跟上一题一样,只是遇到偶数行逆向输出。

/**
 * 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>> ret = new ArrayList<ArrayList<Integer>>();
        boolean order = false;
        if(root == null) return ret;
        LinkedList<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        ArrayList<Integer> first = new ArrayList<Integer>();
        first.add(root.val);
        ret.add(first);
        while(q.size() != 0){
            int i = 0;
            int len = q.size();
            while(i < len){
                TreeNode temp = q.poll();
                if(temp.left != null)
                    q.add(temp.left);
                if(temp.right != null)
                    q.add(temp.right);
                i++;
            }
            if(q.size() > 0){
                ArrayList<Integer> level = new ArrayList<Integer>();
                if(order){
                    for(int index = 0; index < q.size(); index++){
                            level.add(q.get(index).val);
                    }
                }
                else{
                    for(int index = q.size()-1; index >= 0; index--){
                            level.add(q.get(index).val);
                    }
                }
                ret.add(level);
                order = order ? false:true;
            }
        }
        return ret;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s