`

Inorder Successor in BST

    博客分类:
  • Tree
 
阅读更多
[分析]
参考https://leetcode.com/discuss/59728/10-and-4-lines-o-h-java-c
& https://leetcode.com/discuss/59787/share-my-java-recursive-solution
不理解参考代码中为什么最后需要额外判断left.val > p.val

public class Solution {
    // Method 3: recursion
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        while (root != null && root.val <= p.val)
            root = root.right;
        if (root == null) return null;
        TreeNode left = inorderSuccessor(root.left, p);
        return left != null ? left : root;
    }
    public TreeNode inorderPrecessor(TreeNode root, TreeNode p) {
        while (root != null && root.val >= p.val)
            root = root.left;
        if (root == null) return null;
        TreeNode right = inorderPrecessor(root.right, p);
        return right != null ? right : root;
    }
    
    // Method 2: optimize findSuccessor
    private TreeNode findSuccessor(TreeNode root, TreeNode p) {
        TreeNode cand = null; // smallest node which is larger than p, or the last left-turn node
        while (root != null) {
            if (root.val <= p.val) {
                root = root.right;
            } else {
                cand = root;
                root = root.left;
            }
        }
        return cand;
    }
    
    // Method 1: self
    public TreeNode inorderSuccessor1(TreeNode root, TreeNode p) {
        if (root == null || p == null) return null;
        if (p.right != null)
            return findMin(p.right);
        else
            return findSuccessor(root, p);
    }
    private TreeNode findMin(TreeNode root){
        if (root == null) return root;
        while (root.left != null)
            root = root.left;
        return root;
    }
    private TreeNode findSuccessor1(TreeNode root, TreeNode p) {
        LinkedList<TreeNode> path = new LinkedList<TreeNode>();
        TreeNode curr = root;
        while (curr != p) {
            path.push(curr);
            if (p.val > curr.val) {
                curr = curr.right;
            } else {
                curr = curr.left;
            }
        }
        while (!path.isEmpty()) {
            TreeNode cand = path.pop();
            if (cand.val > p.val) return cand;
        }
        return null;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics