Skip to content

Commit 5512ccd

Browse files
committed
0513二叉树左小角的值JavaScript版本
1 parent f5d2d2c commit 5512ccd

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

problems/0513.找树左下角的值.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,53 @@ class Solution:
298298
```
299299
Go:
300300

301+
JavaScript:
302+
1. 递归版本
303+
```javascript
304+
var findBottomLeftValue = function(root) {
305+
//首先考虑递归遍历 前序遍历 找到最大深度的叶子节点即可
306+
let maxPath = 0,resNode = null;
307+
// 1. 确定递归函数的函数参数
308+
const dfsTree = function(node,curPath){
309+
// 2. 确定递归函数终止条件
310+
if(node.left===null&&node.right===null){
311+
if(curPath>maxPath){
312+
maxPath = curPath;
313+
resNode = node.val;
314+
}
315+
// return ;
316+
}
317+
node.left&&dfsTree(node.left,curPath+1);
318+
node.right&&dfsTree(node.right,curPath+1);
319+
}
320+
dfsTree(root,1);
321+
return resNode;
322+
};
323+
```
324+
2. 层序遍历
325+
```javascript
326+
var findBottomLeftValue = function(root) {
327+
//考虑层序遍历 记录最后一行的第一个节点
328+
let queue = [];
329+
if(root===null){
330+
return null;
331+
}
332+
queue.push(root);
333+
let resNode;
334+
while(queue.length){
335+
let length = queue.length;
336+
for(let i=0; i<length; i++){
337+
let node = queue.shift();
338+
if(i===0){
339+
resNode = node.val;
340+
}
341+
node.left&&queue.push(node.left);
342+
node.right&&queue.push(node.right);
343+
}
344+
}
345+
return resNode;
346+
};
347+
```
301348

302349

303350

0 commit comments

Comments
 (0)