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

103. Binary Tree Zigzag Level Order Traversal

时间:2017-06-06 10:34:48      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:problems   ble   lte   style   链接   last   array   题目   turn   

题目:

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

链接: http://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

6/5/2017

2ms, 42%

注意的问题:

1. 第8行leftToRight左右的方向顺序

2. LinkedList addFirst, addLast

 1 public class Solution {
 2     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
 3         List<List<Integer>> ret = new ArrayList<>();
 4         if (root == null) return ret;
 5         
 6         LinkedList<TreeNode> list = new LinkedList<TreeNode>();
 7         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 8         boolean leftToRight = true;
 9         queue.add(root);
10         
11         while (!queue.isEmpty()) {
12             int size = queue.size();
13             List<Integer> temp = new ArrayList<Integer>();
14 
15             for (int i = 0; i < size; i++) {
16                 TreeNode node = queue.poll();
17                 if (leftToRight) {
18                     if (node.left != null) {
19                         list.addFirst(node.left);
20                     }
21                     if (node.right != null) {
22                         list.addFirst(node.right);
23                     }
24                 } else {
25                     if (node.right != null) {
26                         list.addFirst(node.right);
27                     }
28                     if (node.left != null) {
29                         list.addFirst(node.left);
30                     }                    
31                 }
32                 temp.add(node.val);
33             }
34             ret.add(temp);
35             int listSize = list.size();
36             for (int i = 0; i < listSize; i++) {
37                 queue.add(list.poll());
38             }
39             leftToRight = !leftToRight;
40         }
41         return ret;
42     }
43 }

更多讨论

https://discuss.leetcode.com/category/111/binary-tree-zigzag-level-order-traversal

103. Binary Tree Zigzag Level Order Traversal

标签:problems   ble   lte   style   链接   last   array   题目   turn   

原文地址:http://www.cnblogs.com/panini/p/6949510.html

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