算法刷题打卡018 | 二叉搜索树上的双指针

LeetCode 530.二叉搜索树的最小绝对差

题目链接:530. 二叉搜索树的最小绝对差 - 力扣(Leetcode)

二叉搜索树的中序遍历结果有序,而最小绝对差只能存在于相邻两个元素之间,因此用双指针法中序遍历二叉树,每次获得前一个元素和当前元素的差值,取其中的最小值:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.pre = None
        self.res = 10 ** 5 + 1
    
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        # pre = None
        # res = 1e5+1
        def dfs(node):
            if not node:
                return
            dfs(node.left)
            if self.pre is not None:
                self.res = min(self.res, abs(node.val - self.pre.val))
            self.pre = node
            dfs(node.right)
        
        dfs(root)
        return self.res

LeetCode 501.二叉搜索树中的众数

题目链接:501. 二叉搜索树中的众数 - 力扣(Leetcode)

同样是二叉搜索树,中序遍历序列必然有序,且相同元素连续排列,众数需要寻找出现次数最多的值,在中序遍历中通过判断当前节点与pre的值是否相同,计数pre的出现次数。注意遍历到最后的众数无法在循环中收集结果,需要在循环结束之后额外处理(比如测试用例[1, null, 2, 2]):

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        maxcount, count = 0, 1
        result = []
        pre, cur = None, root
        stack = []
        # 迭代法 中序遍历
        while cur or stack:
            if cur:
                # 左
                stack.append(cur)
                cur = cur.left
            else:
                # 中
                cur = stack.pop()
                if pre is not None:
                    if cur.val == pre.val:
                        count += 1
                    else:
                        if count > maxcount:
                            maxcount = count
                            result.clear()
                            result.append(pre.val)
                        elif count == maxcount:
                            result.append(pre.val)
                        count = 1
                pre = cur
                # 右
                cur = cur.right
        # 需要额外处理最后的众数
        if count > maxcount:
            maxcount = count
            result.clear()
            result.append(pre.val)
        elif count == maxcount:
            result.append(pre.val)
        return result

看讲解的写法并不需要额外处理最后的遍历结果,而是调整判断count和maxcount大小关系的部分的位置:

class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        maxcount, count = 0, 1
        result = []
        pre, cur = None, root
        stack = []
        # 迭代法 中序遍历
        while cur or stack:
            if cur:
                # 左
                stack.append(cur)
                cur = cur.left
            else:
                # 中
                cur = stack.pop()
                if pre is not None and cur.val == pre.val:
                    count += 1
                else:        
                    count = 1
                if count > maxcount:
                    maxcount = count
                    result.clear()
                    result.append(pre.val)
                elif count == maxcount:
                    result.append(pre.val)
                pre = cur
                # 右
                cur = cur.right
        return result

LeetCode 236. 二叉树的最近公共祖先

题目链接:236. 二叉树的最近公共祖先 - 力扣(Leetcode)

个人觉得这道题中,如何判断节点是二叉树的最近公共祖先这一点很重要,其次就是递归函数返回值如何确定的问题,掌握思路后代码就比较容易实现了:

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

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # 后序遍历,找左右子树各包含一个节点的第一个节点就是他们的最近公共祖先
        def dfs(node, p, q):
            if not node:
                return None
            elif node == p:
                return p
            elif node == q:
                return q
            left = dfs(node.left, p, q)
            right = dfs(node.right, p, q)
            if left and right:
                return node  # 找到最近公共祖先,返回公共祖先的节点
            elif not left:
                return right
            else:
                return left
        
        res = dfs(root, p, q)
        return res

另外还顺便把相似题目235. 二叉搜索树的最近公共祖先 - 力扣(Leetcode)也一并做完,由于是二叉搜索树,可以直接套用二叉树的做法,但是用迭代法更简单:

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

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        
        while root:
            if p.val < root.val and q.val < root.val:
                # 都比root小
                root = root.left
            elif p.val > root.val and q.val > root.val:
                # 都比root大
                root = root.right
            else:
                # 左右各占一个,必为最近公共祖先
                return root
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值