Question:
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(p.right != null){
return minNode(p.right);
}
TreeNode succ = null;
// Start from root and search for successor down the tree
while(root!= null){
if(p.val < root.val){
succ = root;
root = root.left;
}
else if(p.val > root.val){
root = root.right;
}
else{
break;
}
}
return succ;
}
public TreeNode minNode(TreeNode root){
if(root==null)return null;
TreeNode q = root;
TreeNode p = root.left;
while(p!=null){
q=p;
p=p.left;
}
return q;
}
}
No comments:
Post a Comment