Saturday, February 28, 2015

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,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]
Solution:
在遍历的时候偶数层自左向右,而奇数层自右向左。Binary Tree Level Order Traversal中我们是维护了一个队列来完成遍历,而在这里为了使每次都倒序出来,我们很容易想到用栈的结构来完成这个操作。有一个区别是这里我们需要一层一层的来处理(原来可以按队列插入就可以,因为后进来的元素不会先处理),所以会同时维护新旧两个栈,一个来读取,一个存储下一层结点。总体来说还是一次遍历完成,所以时间复杂度是O(n),空间复杂度最坏是两层的结点,所以数量级还是O(n)(满二叉树最后一层的结点是n/2个)。
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList> zigzagLevelOrder(TreeNode root) {
        ArrayList> res = new ArrayList>();
        if(root == null)
            return res;
        
        ArrayList list = new ArrayList();
        LinkedList stack = new LinkedList();
        list.add(root.val);
        res.add(list);
        stack.push(root);
        int level = 1;
        
        while(!stack.isEmpty()) {
            list = new ArrayList();
            LinkedList newStack = new LinkedList();  //for storing nodes which will be used for next level
            while(!stack.isEmpty()) {
                TreeNode node = stack.pop();
                if(level % 2 == 0) {  //偶数层从左向右
                    if(node.left != null) {
                        newStack.push(node.left);
                        list.add(node.left.val);
                    }
                    if(node.right != null) {
                        newStack.push(node.right);
                        list.add(node.right.val);
                    }
                }else {  //奇数层从右向左
                    if(node.right != null) {
                        newStack.push(node.right);
                        list.add(node.right.val);
                    }
                    if(node.left != null) {
                        newStack.push(node.left);
                        list.add(node.left.val);
                    }
                }
            }
            level++;
            if(list.size() > 0) {
                res.add(list);
            }
            stack = newStack; //assign the newStack to stack, it will be used in next loop
        }
        return res;
    }
}

2 comments:

  1. 搜答案搜到你这里来了,blog写的好认真,赞一个!向你学习!

    ReplyDelete
    Replies
    1. 思路大部分都是网上别人那里搜来的哈哈,主要为了给自己复习用,时间太紧了,不然思路自己认真写写就好了=P

      Delete