标签:UNC tput size htm logs length shift nbsp output
二叉树之字形层序遍历。题意是给一个二叉树,对其进行层序遍历,但是在遍历每一层的时候要一次从左开始一次从右开始。例子,
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] ]
思路和102题的做法 - 层序遍历没两样,唯一需要多一个变量记录到底是从左遍历还是从右遍历。代码如下
时间O(n)
空间O(n) - 记录output
1 /** 2 * @param {TreeNode} root 3 * @return {number[][]} 4 */ 5 var zigzagLevelOrder = function(root) { 6 var res = []; 7 if (root === null) return res; 8 var queue = []; 9 queue.push(root); 10 var x = true; 11 while (queue.length) { 12 var size = queue.length; 13 var list = []; 14 for (var i = 0; i < size; i++) { 15 var cur = queue.shift(); 16 if (x) { 17 list.push(cur.val); 18 } else { 19 list.unshift(cur.val); 20 } 21 if (cur.left !== null) { 22 queue.push(cur.left); 23 } 24 if (cur.right !== null) { 25 queue.push(cur.right); 26 } 27 } 28 res.push(list); 29 x = !x; 30 } 31 return res; 32 };
[LeetCode] 103. Binary Tree Zigzag Level Order Traversal
标签:UNC tput size htm logs length shift nbsp output
原文地址:https://www.cnblogs.com/aaronliu1991/p/12267512.html