Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
一刷
题解:
类似于binary search,我们要找一个大于该点的最小值。
/**
* 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) return null;
if(root.val<p.val) return inorderSuccessor(root.right, p);
else{
TreeNode left = inorderSuccessor(root.left, p);
return (left!=null)? left:root;
}
}
}
二刷
/**
* 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) return null;
if(root.val<=p.val) return inorderSuccessor(root.right, p);
else{
TreeNode left = inorderSuccessor(root.left, p);
if(left == null) return root;
else return left;
}
}
}