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

[解题思路]

本题是二叉树层序遍历的变形,二叉树的层序遍历通过使用queue来实现,

一开始我也试图用queue来解这题,第二层很好解决,但到第三层时无法实现从左到右遍历该层

上网搜索了下,发现该题可以使用栈来解决,通过分析执行结果确实是后进先出

这里通过定义leftToRight来表示是从左到右还是从右到左

从左到右:先加left后加right

从右到左:先加right后加left

 1 public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 5         if(root == null){
 6             return result;            
 7         }
 8         Stack<TreeNode> curLvl = new Stack<TreeNode>();
 9         Stack<TreeNode> nextLvl = new Stack<TreeNode>();
10         boolean leftToRight = true;
11         curLvl.push(root);
12         ArrayList<Integer> output = new ArrayList<Integer>();
13         while(!curLvl.empty()){
14             TreeNode curNode = curLvl.pop();
15             output.add(curNode.val);
16             if(leftToRight){
17                 if(curNode.left != null){
18                     nextLvl.add(curNode.left);
19                 }
20                 if(curNode.right != null){
21                     nextLvl.add(curNode.right);
22                 }
23             } else{
24                 if(curNode.right != null){
25                     nextLvl.add(curNode.right);
26                 }
27                 if(curNode.left != null){
28                     nextLvl.add(curNode.left);
29                 }
30             }
31             if(curLvl.empty()){
32                 result.add(output);
33                 output = new ArrayList<Integer>();
34                 leftToRight = !leftToRight;
35                 curLvl.addAll(nextLvl);
36                 nextLvl.clear();
37             }
38         }
39         return result;
40     }

 

posted @ 2013-08-23 22:10  feiling  阅读(245)  评论(0编辑  收藏  举报