日野弥生:勉強しよう

LeetCode 993 - 二叉树的堂兄弟节点

发表于2025年03月24日

#树 #二叉树 #深度优先搜索 #广度优先搜索

先根遍历的思想,只是需要带父节点的参数到下一个节点的遍历过程中。同时满足父节点值不相同和节点深度相同即可满足条件。

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        # 记录值进哈希表里
        targets = {x, y}
        # 结果返回存储
        parrentNodeAndDepth = []

        # 进入遍历前要先保证根不为空且根节点值不在哈希表里
        if not root or root.val in targets:
            return False
        
        def isCousinsIMPL(parrent: Optional[TreeNode], root: Optional[TreeNode], depth: int):
            nonlocal parrentNodeAndDepth

            # 当前节点如果为空则返回
            if not root:
                return
            # 如果存在,则记录父节点值和当前节点深度
            if root.val in targets:
                parrentNodeAndDepth.append([depth, parrent.val])
            
            # 递归时,深度+1,同时把父节点向下传递
            isCousinsIMPL(root, root.left, depth + 1)
            isCousinsIMPL(root, root.right, depth + 1)
                
        isCousinsIMPL(None, root, 0)
        itemX = parrentNodeAndDepth[0]
        itemY = parrentNodeAndDepth[1]
        # 同时满足父节点值不相同和节点深度相同
        return itemX[0] == itemY[0] and itemX[1] != itemY[1]

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/cousins-in-binary-tree/

上一篇

LeetCode 235 - 二叉搜索树的最近公共祖先

下一篇

LeetCode 671 - 二叉树中第二小的节点