Skip to content

Commit 70a1c89

Browse files
committed
Create 1373.二叉搜索子树的最大键值和.js
1 parent 5982d36 commit 70a1c89

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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 maxSumBST = 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+
if (left === null || right === null || (node.left && node.left.val >= node.val) || (node.right && node.right.val <= node.val)) {
21+
return null;
22+
}
23+
const sum = left + right + node.val;
24+
result = Math.max(result, sum);
25+
return sum;
26+
}
27+
dfs(root);
28+
return result;
29+
};
30+
31+
console.log(maxSumBST(arrayToTree([5,4,8,3,null,6,3])));
32+
33+
function arrayToTree(arr) {
34+
function TreeNode(val) {
35+
this.val = val;
36+
this.left = this.right = null;
37+
}
38+
if (arr.length === 0) {
39+
return null;
40+
}
41+
const root = new TreeNode(arr[0]);
42+
const list = [root];
43+
let i = 1;
44+
while (list.length > 0) {
45+
const node = list.shift();
46+
if (typeof arr[i] === 'number') {
47+
node.left = new TreeNode(arr[i]);
48+
list.push(node.left);
49+
}
50+
i++;
51+
if (typeof arr[i] === 'number') {
52+
node.right = new TreeNode(arr[i]);
53+
list.push(node.right);
54+
}
55+
i++;
56+
}
57+
return root;
58+
}

0 commit comments

Comments
 (0)