Inorder Successor in BST

[分析]
参考[url]https://leetcode.com/discuss/59728/10-and-4-lines-o-h-java-c[/url]
& [url]https://leetcode.com/discuss/59787/share-my-java-recursive-solution[/url]
不理解参考代码中为什么最后需要额外判断left.val > p.val


public class Solution {
// Method 3: recursion
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
while (root != null && root.val <= p.val)
root = root.right;
if (root == null) return null;
TreeNode left = inorderSuccessor(root.left, p);
return left != null ? left : root;
}
public TreeNode inorderPrecessor(TreeNode root, TreeNode p) {
while (root != null && root.val >= p.val)
root = root.left;
if (root == null) return null;
TreeNode right = inorderPrecessor(root.right, p);
return right != null ? right : root;
}

// Method 2: optimize findSuccessor
private TreeNode findSuccessor(TreeNode root, TreeNode p) {
TreeNode cand = null; // smallest node which is larger than p, or the last left-turn node
while (root != null) {
if (root.val <= p.val) {
root = root.right;
} else {
cand = root;
root = root.left;
}
}
return cand;
}

// Method 1: self
public TreeNode inorderSuccessor1(TreeNode root, TreeNode p) {
if (root == null || p == null) return null;
if (p.right != null)
return findMin(p.right);
else
return findSuccessor(root, p);
}
private TreeNode findMin(TreeNode root){
if (root == null) return root;
while (root.left != null)
root = root.left;
return root;
}
private TreeNode findSuccessor1(TreeNode root, TreeNode p) {
LinkedList<TreeNode> path = new LinkedList<TreeNode>();
TreeNode curr = root;
while (curr != p) {
path.push(curr);
if (p.val > curr.val) {
curr = curr.right;
} else {
curr = curr.left;
}
}
while (!path.isEmpty()) {
TreeNode cand = path.pop();
if (cand.val > p.val) return cand;
}
return null;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值