var findBottomLeftValue = function (root) { let rust = root.val let curLevel = [] if (root) curLevel.push(root) while (curLevel.length) { let nextLevel = [] for (let i = 0; i < curLevel.length; i++) { let cur = curLevel[i] if (cur.left) nextLevel.push(cur.left) if (cur.right) nextLevel.push(cur.right) } if (nextLevel[0]) rust = nextLevel[0].val; curLevel = nextLevel } return rust};
解法二
产品经理大法好
DFS
时间复杂度 O(n) n 指深度
空间复杂度 O(1) 2 个常数空间
var findBottomLeftValue = function (root) { let rust = root.val let maxDepth = 0 let left = dfs(root.left, 0) let right = dfs(root.right, 0) function dfs(cur, depth) { if (!cur) return let curDepth = depth + 1 if (curDepth > maxDepth) { maxDepth = curDepth rust = cur.val } dfs(cur.left, curDepth) dfs(cur.right, curDepth) } return rust};
参考回答
BFS
其实问题本身就告诉你怎么做了
在树的最后一行找到最左边的值。
问题再分解一下
找到树的最后一行
找到那一行的第一个节点
不用层序遍历简直对不起这个问题,这里贴一下层序遍历的流程
令curLevel为第一层节点也就是root节点定义nextLevel为下层节点遍历node in curLevel, nextLevel.push(node.left) nextLevel.push(node.right)令curLevel = nextLevel, 重复以上流程直到curLevel为空var findBottomLeftValue = function (root) { let curLevel = [root]; let res = root.val; while (curLevel.length) { let nextLevel = []; for (let i = 0; i < curLevel.length; i++) { curLevel[i].left && nextLevel.push(curLevel[i].left); curLevel[i].right && nextLevel.push(curLevel[i].right); } res = curLevel[0].val; curLevel = nextLevel; } return res;};