Binary Tree Zigzag Level Order Traversal
Posted beiyeqingteng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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,null,null,15,7]
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
分析:用一个flag来表示存入list的方向即可。
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>> allLists = new ArrayList<>(); 13 if (root == null) return allLists; 14 15 List<Integer> temp = new LinkedList<>(); 16 List<TreeNode> list1 = new LinkedList<>(); 17 List<TreeNode> list2 = new LinkedList<>(); 18 19 list1.add(root); 20 int direction = 1; 21 22 while(list1.size() != 0) { 23 for (TreeNode node : list1) { 24 if (direction == 1) { 25 temp.add(node.val); 26 } else { 27 temp.add(0, node.val); 28 } 29 if (node.left != null) list2.add(node.left); 30 if (node.right != null) list2.add(node.right); 31 } 32 allLists.add(new LinkedList<Integer>(temp)); 33 temp.clear(); 34 list1 = list2; 35 list2 = new ArrayList<TreeNode>(); 36 direction *= -1; 37 } 38 return allLists; 39 } 40 }
以上是关于Binary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
树Binary Tree Zigzag Level Order Traversal
LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告
[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal
Binary Tree Zigzag Level Order Traversal