Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active September 3, 2017 18:41
Show Gist options
  • Save cixuuz/11db60e446adc2da9c05b0ca00f463ea to your computer and use it in GitHub Desktop.
Save cixuuz/11db60e446adc2da9c05b0ca00f463ea to your computer and use it in GitHub Desktop.
[285. Inorder Successor in BST] #leetcode
// O(n) O(1)
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null) return null;
TreeNode succ = null;
Deque<TreeNode> stack = new LinkedList<TreeNode>();
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.right;
} else {
TreeNode node = stack.pop();
if (node == p) return succ;
succ = node;
root = node.left;
}
}
return succ;
}
}
// O(log(n))
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode succ = null;
while (root != null) {
if (p.val < root.val) {
succ = root;
root = root.left;
}
else
root = root.right;
}
return succ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment