Leetcode笔记 每日一题 面试题 04.06. 后继者 (22.05.16)

Leetcode笔记 每日一题 面试题 04.06. 后继者 (22.05.16)

Leetcode 每日一题 面试题 04.06. 后继者 (22.05.16)

题目

设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。

如果指定节点没有对应的“下一个”节点,则返回null。

示例 1:

输入: root = [2,1,3], p = 1

  2
 / \
1   3

输出: 2

示例 2:

输入: root = [5,3,6,2,4,null,null,1], p = 6

     5
    / \
   3   6
  / \
 2   4
/  
1

输出: null

解题思路

题目求的是中序后继,即目标节点p的下一个节点的值并返回。我们可以理解为二叉树root中比目标节点p大的的节点中的最小一个。所以可以对root进行中序遍历,因为二叉搜索树的中序遍历,节点是从小到大依次排列的。然后判断中序遍历后是否存在root[i] == p,如果存在则返回root[i+1],如果不存在则返回None


Python代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
        res = []  # 用来存储中序遍历的值
        # 中序遍历 -- 递归
        def inorder(root):
            if not root:
                return None
            inorder(root.left)
            res.append(root)
            inorder(root.right)
            return res
        inorder(root)
        for i in range(len(res)-1):
            if res[i] == p:
                return res[i+1]
        return None

另一种方法:可以用递归方法解决,参考:【负雪明烛】图解算法:思路 + 递归过程
根据二叉搜索树的性质:左子树的值会比当前节点小,右子树会比当前节点大。因此:

  • root.val <= p.val时,我们要在当前root的右子树中寻找
  • 如果root.val > p.val,则在左子树中寻找
  • 如果不存在,则返回None

class Solution:
    def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
        def dfs(root, p):
            if not root:
                return None
            if root.val <= p.val:  
                return dfs(root.right, p)
                
            left = dfs(root.left, p)
            return left if left else root
       
        return dfs(root, p)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值