方法1: simulate an inorder traversal。新建一个全局stack。对于每个node,我们先放node.right,再放node,最后放node.left。最后我们遍历stack,这样pop出来的顺序正好就是inorder traversal的顺序。时间复杂n,空间复杂n。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Stack<TreeNode> stack = new Stack<>();
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root == null) return null;
inorder(root);
while(!stack.isEmpty()){
TreeNode curr = stack.pop();
if(curr == p && !stack.isEmpty()) return stack.pop();
}
return null;
}
public void inorder(TreeNode root){
if(root == null){
return;
}
inorder(root.right);
stack.push(root);
inorder(root.left);
}
}
方法2: 上面我的方法并没有用到bst这个性质,方法二非常巧妙的运用了bst。时间复杂n,空间复杂1.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// Solution: BST
// Use the BST characteristic to find the smallest node
// larger than p
// Time complexity: O(n) -- traverse all nodes
// Space complexity: O(1)
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null || p == null) {
return null;
}
TreeNode successor = null;
while (root != null) {
if (root.val > p.val) {
successor = root;
root = root.left;
} else {
root = root.right;
}
}
return successor;
}
}
总结:
- 无