File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * class TreeNode {
4
+ * val: number
5
+ * left: TreeNode | null
6
+ * right: TreeNode | null
7
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8
+ * this.val = (val===undefined ? 0 : val)
9
+ * this.left = (left===undefined ? null : left)
10
+ * this.right = (right===undefined ? null : right)
11
+ * }
12
+ * }
13
+ * /
14
+
15
+ function findSecondMinimumValue(root: TreeNode | null): number {
16
+ if (!root.left) {
17
+ return -1;
18
+ }
19
+ return dfs(root, root.val, -1);
20
+ };
21
+
22
+ function dfs(
23
+ root: TreeNode,
24
+ minValue: number,
25
+ result: number,
26
+ ): number {
27
+
28
+ if (root.val > minValue) {
29
+ result = Math.min(result !== -1 ? result : root.val, root.val);
30
+ }
31
+
32
+ root.left && (result = dfs(root.left, minValue, result));
33
+ root.right && (result = dfs(root.right, minValue, result));
34
+
35
+ return result;
36
+ }
You can’t perform that action at this time.
0 commit comments