您的位置:首页 > 其它

Inorder Successor in Binary Search Tree

2016-08-07 00:05 344 查看
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

public class Solution {

public TreeNode inorderSuccessor(TreeNode root, TreeNode n) {
if (root == null) return null;

if (n.right != null) {
return min(n.right);
}

TreeNode succ = null;
while (root != null) {
if (n.val < root.val) { //左子树的successor都是当前树的root。
succ = root;
root = root.left;
} else if (n.val > root.val)
root = root.right;
else
break;
}
return succ;
}

public TreeNode min(TreeNode n) {
if (n.left != null) {
return min(n.left);
}
return n;
}
}

class TreeNode {
TreeNode left;
TreeNode right;
int val;

public TreeNode(int i) {
val = i;
}
}


Another solution

public class Solution {
TreeNode pre = null;
TreeNode succ = null;

void inorderSuccessorII(TreeNode root, TreeNode p) {
if (root == null || succ != null)
return;
inorderSuccessor(root.left, p);
if (pre == p) {
succ = root;
}
pre = root;
inorderSuccessor(root.right, p);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: