Last active
September 3, 2017 18:41
-
-
Save cixuuz/11db60e446adc2da9c05b0ca00f463ea to your computer and use it in GitHub Desktop.
[285. Inorder Successor in BST] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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