Question
Given a binary search tree and a node in it, find the In-order successor of this node in the BST.
Note:if The given node has a no In-order successor in the tree, return null
.
Solution--Iterative
Inorder result is a ascending array for BST. Thus, this problem can is transferred to find successor for a node in BST.
successor = first element is greater than target node.
Consider situations:
1. Target node has right child
2. Target node doesn ' t has right child
Trace back, find first node whose left child was in the path from target node to root.
For this situation:
1. If node has the parent pointer, we just use the parent pointer.
2. If node doesn ' t has the parent pointer, we use the stack.
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicTreeNode inordersuccessor (TreeNode root, TreeNode p) { A //same question with finding successor in a BST - //1. If P has right child, find minimum child in right subtree - //2. If p doesn ' t has right child, find first ancestor whose left child is in the path from p to root. theTreeNode result =NULL; - if(P.right! =NULL) { -result =P.right; - while(Result.left! =NULL) { +result =Result.left; - } +}Else { Adeque<treenode> stack =NewLinkedlist<treenode>(); atTreeNode current =Root; - //push to Stack - while(Current! = P && Current! =NULL) { - Stack.push (current); - if(P.val <current.val) { -Current =Current.left; in}Else { -Current =Current.right; to } + } - //Pop Stack theTreeNode prev =p; * while(!Stack.isempty ()) { $TreeNode cur =Stack.pop ();Panax Notoginseng if(Cur.left = =prev) { -result =cur; the Break; + } APrev =cur; the } + } - returnresult; $ } $}
Solution 2--Recursive
Find successor & predecessor in BST
Inorder successor in BST solution