Given a binary search tree (See Definition) and a node in it, find the in-order successor of that node in the BST.
If the given node has no in-order successor in the tree, return null
.
使用中序遍历的方式进行求解
java
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null || p == null) {
return null;
}
List<TreeNode> path = inOrder(root);
int index = path.indexOf(p);
return index == -1 || index == path.size() - 1 ? null : path.get(index + 1);
}
private List<TreeNode> inOrder(TreeNode root) {
List<TreeNode> result = new ArrayList<>();
if (root == null) {
return result;
}
List<TreeNode> left = inOrder(root.left);
List<TreeNode> right = inOrder(root.right);
result.addAll(left);
result.add(root);
result.addAll(right);
return result;
}
}
使用二叉树的性质进行求解
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null || p == null) {
return null;
}
if (root.val <= p.val) {
return inorderSuccessor(root.right, p);
} else {
TreeNode left = inorderSuccessor(root.left, p);
return left == null ? root : left;
}
}
}