描述
给出一棵二叉搜索树以及其中的一个节点,找到这个节点在这棵树中的中序前驱节点。
在线评测地址:领扣题库官网
样例1
输入: root = {2,1,3}, p = 1
输出: null
样例2
输入: root = {2,1}, p = 2
输出: 1
用while循环模拟递归
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the given BST
* @param p: the given node
* @return: the in-order successor of the given node in the BST
*/
public TreeNode inorderPredecessor(TreeNode root, TreeNode p) {
// write your code here
TreeNode succ = null;
while (root != null) {
if (p.val <= root.val) {
root = root.left;
} else {
if(succ == null || root.val > succ.val){
succ = root;
}
root = root.right;
}
}
return succ;
}
}
更多题解参考:九章官网solution