File tree 1 file changed +27
-0
lines changed
1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ import classes .TreeNode ;
4
+
5
+ /**285. Inorder Successor in BST
6
+
7
+ Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
8
+
9
+ Note: If the given node has no in-order successor in the tree, return null. */
10
+ public class InorderSuccessorInBST {
11
+
12
+ //Amazed at this solution: https://discuss.leetcode.com/topic/25698/java-python-solution-o-h-time-and-o-1-space-iterative
13
+ //I used brute force: traverse the tree and store and nodes in a list, then traverse the list to compare with p to return the successor if there is.
14
+ public TreeNode inorderSuccessor (TreeNode root , TreeNode p ) {
15
+ TreeNode succ = null ;
16
+ while (root != null ){
17
+ if (p .val < root .val ){
18
+ succ = root ;
19
+ root = root .left ;
20
+ } else {
21
+ root = root .right ;
22
+ }
23
+ }
24
+ return succ ;
25
+ }
26
+
27
+ }
You can’t perform that action at this time.
0 commit comments