103. Binary Tree Zigzag Level Order Traversal

Posted panini

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了103. 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]
]

链接: 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的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal

LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告

[leetcode tree]103. Binary Tree Zigzag Level Order Traversal

[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal