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     }

 

转载于:https://www.cnblogs.com/feiling/p/3278691.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值