Friday, November 6, 2015

Inorder Successor in BST -- Leetcode

Question:
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
Answer:
 * 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