LeetCode – Inorder Successor in BST (Java)
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
// Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } |
Java Solution
The node does not have a pointer pointing to its parent. This is different from Inorder Successor in BST II.
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { if(root==null) return null; TreeNode next = null; TreeNode c = root; while(c!=null && c.val!=p.val){ if(c.val > p.val){ next = c; c = c.left; }else{ c= c.right; } } if(c==null) return null; if(c.right==null) return next; c = c.right; while(c.left!=null) c = c.left; return c; } |
When the tree is balanced, time complexity is O(log(n)) and space is O(1). The worst case time complexity is O(n).
<pre><code> String foo = "bar"; </code></pre>
-
priyanka nagpal
-
Subodh Karwa
-
Udaydeep Thota