网易面试题: BST 的中序前驱节点
資深大佬 : zzzrf 2
描述
给出一棵二叉搜索树以及其中的一个节点,找到这个节点在这棵树中的中序前驱节点。 在线评测地址
样例 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; } }
更多题解参考
大佬有話說 (0)