Skip to content

Commit 181940a

Browse files
committed
Create 543.二叉树的直径.js
1 parent 2538757 commit 181940a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

543.二叉树的直径.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number}
11+
*/
12+
var diameterOfBinaryTree = function(root) {
13+
let result = 0;
14+
function dfs(node) {
15+
if (!node) {
16+
return 0;
17+
}
18+
const left = dfs(node.left);
19+
const right = dfs(node.right);
20+
result = Math.max(result, left + right);
21+
return 1 + Math.max(left, right);
22+
}
23+
dfs(root);
24+
return result;
25+
};

0 commit comments

Comments
 (0)