Description
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
.
Solution
题目要审清楚:
- BST
- Successor是后继者
Stack, time O(n), space O(n)
这种解法是binary tree通用的,没有考虑bst的特性。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null || p == null) {
return null;
}
Stack<TreeNode> stack = new Stack<>();
pushAllLeft(root, stack);
boolean found = false;
while (!stack.empty()) {
TreeNode curr = stack.pop();
if (curr == p) {
found = true;
} else if (found) {
return curr;
}
pushAllLeft(curr.right, stack);
}
return null;
}
public void pushAllLeft(TreeNode node, Stack<TreeNode> stack) {
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
Recursive + Binary search, time O(h), space O(1)
考虑bst特性进行二分。其实就是想在bst中找到第一个大于p.val的节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null || p == null) {
return null;
}
if (p.val >= root.val) {
return inorderSuccessor(root.right, p);
} else {
TreeNode left = inorderSuccessor(root.left, p);
return left != null ? left : root;
}
}
}