您的位置:首页 > 其它

285. Inorder Successor in BST

2015-12-11 08:07 501 查看
题目:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: