标签:https 复杂度 cti let html str its col number
二叉树层序遍历二。题意跟版本一很接近,唯一的不同点是输出的output需要从下往上排列,叶子节点层最先输出,根节点在最后输出。例子,
For example:
Given binary tree[3,9,20,null,null,15,7]
,3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
因为跟版本一很接近我就不过多解释思路了,依然是BFS和DFS两种做法。两种做法的时间和空间复杂度均为O(n)。
BFS
1 /** 2 * @param {TreeNode} root 3 * @return {number[][]} 4 */ 5 var levelOrderBottom = function (root) { 6 let res = []; 7 if (root === null) return res; 8 let queue = []; 9 queue.push(root); 10 while (queue.length) { 11 let size = queue.length; 12 let list = []; 13 for (let i = 0; i < size; i++) { 14 let cur = queue.shift(); 15 if (cur.left !== null) queue.push(cur.left); 16 if (cur.right !== null) queue.push(cur.right); 17 list.push(cur.val); 18 } 19 res.unshift(list); 20 } 21 return res; 22 };
DFS
1 /** 2 * @param {TreeNode} root 3 * @return {number[][]} 4 */ 5 var levelOrderBottom = function (root) { 6 let res = []; 7 if (root === null) return res; 8 helper(res, root, 0); 9 return res; 10 }; 11 12 var helper = function (res, root, level) { 13 if (root === null) return; 14 if (level >= res.length) { 15 res.unshift([]); 16 } 17 res[res.length - level - 1].push(root.val); 18 helper(res, root.left, level + 1); 19 helper(res, root.right, level + 1); 20 };
[LeetCode] 107. Binary Tree Level Order Traversal II
标签:https 复杂度 cti let html str its col number
原文地址:https://www.cnblogs.com/aaronliu1991/p/12293630.html