标签:bsp null span link tree add example tween code
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
标签:bsp null span link tree add example tween code
原文地址:https://www.cnblogs.com/beiyeqingteng/p/10468673.html