码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Zigzag Level Order Traversal 解答

时间:2015-09-24 08:16:34      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

Question

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

Traditional way is to use two queues to implement level order traversal. Here, we just add a flag to indicate whether it‘s from left to right or from right to left.

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
12         List<List<Integer>> result = new ArrayList<List<Integer>>();
13         if (root == null)
14             return result;
15         // Set a flag to help judge traversal sequence
16         // flag = 0, from left to right; flag = 1, from right to left
17         int flag = 0;
18         List<TreeNode> current = new ArrayList<TreeNode>();
19         List<TreeNode> next;
20         current.add(root);
21         
22         while (current.size() > 0) {
23             List<Integer> oneRecord = new ArrayList<Integer>();
24             next = new ArrayList<TreeNode>();
25             for (TreeNode tmpNode : current) {
26                 if (tmpNode.left != null)
27                     next.add(tmpNode.left);
28                 if (tmpNode.right != null)
29                     next.add(tmpNode.right);
30                 if (flag == 0)
31                     oneRecord.add(tmpNode.val);
32                 else
33                     oneRecord.add(0, tmpNode.val);
34             }
35             result.add(oneRecord);
36             current = next;
37             flag = 1 - flag;
38         }
39         return result;
40     }
41 }

 

Binary Tree Zigzag Level Order Traversal 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4834105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!