您的位置:首页 > 其它

Inorder Successor in BST

2016-08-04 09:50 274 查看
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
.

最终思想就是,next element分两种,

1. 如果node有右子树,next successor就是右孩子的最左的孩子。

2. 如果node没有右node,那么next successor就是这条树枝向上,最后一个左拐的node。所以,需要用一个node去记录每次左拐,他的parent。

        10

      /

    4

      \

        5

           \

            6

              \

               7

思路,就是如果node有right tree,搜right tree的最左边点,如果没有,那么从root开始搜到p,然后只要左拐,就记录update一下succ,最后找到了,return succ就可以了。

/**
 * 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(root == null || p == null) return null;
        TreeNode succ = null;
        if(p.right!=null){
            return minLeftNode(p.right);
        } else {
            while(root.val != p.val){
                if(root.val > p.val){
                    succ = root;
                    root = root.left;
                } else { // root.val < p.val;
                    root = root.right;
                }
            }
            return succ;
        }
    }
    
    public TreeNode minLeftNode(TreeNode n) {
        if(n == null) return null;
        TreeNode node = n;
        while(node!=null && node.left!=null){
            node = node.left;
        }
        return node;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: