Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
The successor of a node p
is the node with the smallest key greater than p.val
.
Example 1:
imageInput: root = [2,1,3], p = 1
Output: 2
Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
==================================================================================
Example 2:
imageInput: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null
.
Note:
- If the given node has no in-order successor in the tree, return
null
. - It's guaranteed that the values of the tree are unique.
Solution : 中序遍历
1。中序遍历,过程中记录prev node
, 同时检查prev node
是否与给定的p node
值相同,如果相同,那么当前的节点就是inorder successor.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode[] successor = {null};
TreeNode[] prev = {null};
inorderSuccessorHelper (root, p, successor, prev);
return successor[0];
}
public boolean inorderSuccessorHelper (TreeNode root, TreeNode p, TreeNode[] successor, TreeNode[] prev) {
if (root == null) {
return false;
}
// in-prder: first left subtree and find the prev node
if (inorderSuccessorHelper (root.left, p, successor, prev))
return true;
// check if prev is equal to p. if yes, then current node is the successor;
// if not, update the prev node
if (prev[0] != null && prev[0].val == p.val) {
successor[0] = root;
// prev[0] = root;
// System.out.println (successor[0].val);
return true;
}
prev[0] = root;
if (inorderSuccessorHelper (root.right, p, successor, prev))
return true;
return false;
}
}
网友评论