Skip to content

Commit 64c6d84

Browse files
committed
Add solution #510
1 parent 6ff5d00 commit 64c6d84

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,7 @@
498498
507|[Perfect Number](./solutions/0507-perfect-number.js)|Easy|
499499
508|[Most Frequent Subtree Sum](./solutions/0508-most-frequent-subtree-sum.js)|Medium|
500500
509|[Fibonacci Number](./solutions/0509-fibonacci-number.js)|Easy|
501+
510|[Inorder Successor in BST II](./solutions/0510-inorder-successor-in-bst-ii.js)|Medium|
501502
513|[Find Bottom Left Tree Value](./solutions/0513-find-bottom-left-tree-value.js)|Medium|
502503
514|[Freedom Trail](./solutions/0514-freedom-trail.js)|Hard|
503504
515|[Find Largest Value in Each Tree Row](./solutions/0515-find-largest-value-in-each-tree-row.js)|Medium|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 510. Inorder Successor in BST II
3+
* https://leetcode.com/problems/inorder-successor-in-bst-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a node in a binary search tree, return the in-order successor of that node in the BST.
7+
* If that node has no in-order successor, return null.
8+
*
9+
* The successor of a node is the node with the smallest key greater than node.val.
10+
*
11+
* You will have direct access to the node but not to the root of the tree. Each node will have
12+
* a reference to its parent node. Below is the definition for Node:
13+
*
14+
* class Node {
15+
* public int val;
16+
* public Node left;
17+
* public Node right;
18+
* public Node parent;
19+
* }
20+
*/
21+
22+
/**
23+
* // Definition for a _Node.
24+
* function _Node(val) {
25+
* this.val = val;
26+
* this.left = null;
27+
* this.right = null;
28+
* this.parent = null;
29+
* };
30+
*/
31+
32+
/**
33+
* @param {_Node} node
34+
* @return {_Node}
35+
*/
36+
var inorderSuccessor = function(node) {
37+
if (node.right) {
38+
let successor = node.right;
39+
while (successor.left) {
40+
successor = successor.left;
41+
}
42+
return successor;
43+
}
44+
45+
let current = node;
46+
while (current.parent && current.parent.right === current) {
47+
current = current.parent;
48+
}
49+
return current.parent;
50+
};

0 commit comments

Comments
 (0)