LeetCode刷题笔记 面试题 04.06. 后继者

题目描述

设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。

示例:
输入: root = [5,3,6,2,4,null,null,1], p = 4
LeetCode刷题笔记 面试题 04.06. 后继者_第1张图片
输出: 5

Sample Code

class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) return null;
        
        // 当前节点值小于等于目标值,那么当前目标值的后继者必然在右子树
        // 或为某个上层节点(会返回null, 会由下面最后一句处理)
        if(root.val <= p.val)
            return inorderSuccessor(root.right, p);
        TreeNode node = inorderSuccessor(root.left, p);
        return node == null ? root : node;
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/successor-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

你可能感兴趣的:(LeetCode笔记,#,二叉树,#,递归)