首页 > 其他 > 详细

285. Inorder Successor in BST

时间:2015-12-11 08:33:54      阅读:265      评论:0      收藏:0      [点我收藏+]

题目:

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.

链接: http://leetcode.com/problems/inorder-successor-in-bst/

题解:

一开始的想法就是用inorder traversal,设置一个boolean变量,当找到root.val = p.val的时候返回下一个节点,遍历完毕以后返回null。

Time Complexity - O(n), Space Complexity - O(n)

/**
 * 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;
        }
        boolean foundNodeP = false;
        Stack<TreeNode> stack = new Stack<>();
        while(root != null || !stack.isEmpty()) {
            if(root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                if(foundNodeP) {
                    return root;
                }
                if(root.val == p.val) {
                    foundNodeP = true;
                }
                root = root.right;
            }
        }
        
        return null;
    }
}

 

看了Discuss之后发现有很多简洁的写法,而且不用遍历全部元素。利用BST的性质,比较root.val和p.val,然后在左子树或者右子树中查找。

Time Complexity - O(h), Space Complexity - O(1)

/**
 * 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 successor = null;
        while(root != null) {
            if(p.val < root.val) {
                successor = root;
                root = root.left;
            } else {
                root = root.right;
            }
        }
        
        return successor;
    }
}

 

 

Reference:

https://leetcode.com/discuss/69200/for-those-who-is-not-so-clear-about-inorder-successors

https://leetcode.com/discuss/61105/java-python-solution-o-h-time-and-o-1-space-iterative

https://leetcode.com/discuss/59728/10-and-4-lines-o-h-java-c

https://leetcode.com/discuss/59787/share-my-java-recursive-solution

 

285. Inorder Successor in BST

原文:http://www.cnblogs.com/yrbbest/p/5037889.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!