【BST】面试题 04.06. 后继者
题目:
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例 1:
输入: root = [2,1,3], p = 1
2
/ \
1 3
输出: 2
解答:
方法一:使用递归,用一个pre变量记录中序遍历的父亲节点,当父亲节点==p时,当前节点即为要找的节点
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { TreeNode pre = null; TreeNode res = null; public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { inorder(root, p); return res; } public void inorder(TreeNode root,TreeNode p){ if(root == null){ return; } inorder(root.left,p); if(pre == p){ res = root; } pre = root; inorder(root.right,p); } }
方法二:(这个才是要真正要掌握的)
BST的查找,不使用递归
利用BST的性质在二叉搜索树中查找某个符合条件的节点,
从根节点开始查找,每个节点有两条路,左子树,右子树,左子树小于根节点,右子树大于根节点
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { //利用BST的性质在二叉搜索树中查找某个符合条件的节点, //从根节点开始查找,每个节点有两条路,左子树,右子树,左子树小于根节点,右子树大于根节点 //不使用递归 public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { //问题的本质是找到最靠近p节点且值大于p节点值的那个节点 TreeNode res = root; //设定临时变量方便对树的操作 TreeNode cur = root; while(cur!=null){ //如果当前节点的值小于等于目标节点的值,那一定不是答案节点,且答案节点在该节点的右孩子中 if(cur.val<=p.val){ cur = cur.right; }//如果当前节点的值大于目标节点的值,那么该节点有可能是答案节点, //具体是不是需要遍历其左孩子,寻找更靠近p节点值的答案 else{ res = cur; cur = cur.left; } } return res.val<=p.val? null:res; } }