Leetcode May Challenge - 05/07: Cousins in Binary Tree(Python)

题目描述

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.

例子

Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
在这里插入图片描述
Example 2:
在这里插入图片描述
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true

Example 3:
在这里插入图片描述
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

解释

给一颗树和两个节点的值。判断这两个节点是不是cousin。Cousin的定义是两个节点的深度一样,即到根节点的路径长度一样,但父节点不一样。

思路

递归 DFS

简单来说,我们可以分别找出两个值对应的节点的深度和父节点,然后进行比较即可。
具体怎么找呢?咱们可以定义一个函数来做DFS寻找所需节点。如果找到该节点则将该节点的父节点和深度分别存入一个变量。对两个值分别调用这个DFS函数,最后比较两个节点的父节点和深度即可。
在实际操作中,对当前节点寻找父节点实际上是不方便的。因为Tree Node中并没有存Parent的信息,但每个Node中是存了left子节点和right子节点的,所以我们考虑在当前节点不对当前节点进行验证而是对左右子节点进行验证,这样会方便很多。具体见代码注释。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isCousins(self, root, x, y):
        """
        :type root: TreeNode
        :type x: int
        :type y: int
        :rtype: bool
        """
        #定义存x,y寻找结果的变量
        #初始值设为根节点以及根节点的深度0
        #这是因为在dfs中我们不对当前节点进行验证
        #因此根节点在dfs中无法被验证到
        #所以我们初始设为根节点
        #如果根节点不符合要求,则在某一个节点一定会修改该值
        #如果根节点符合要求,则该值会一直保留到最后
        res_x, res_y = [root.val, 0], [root.val, 0]
        #分别寻找x,y对应节点
        self.dfs(root, x, 0, res_x)
        self.dfs(root, y, 0, res_y)
        #判断是否是cousin
        return res_x[0] != res_y[0] and res_x[1] == res_y[1]
        
    #node:传入需要寻找的值,即x或y
    #res:即res_x或res_y
    def dfs(self, root, node, depth, res):
        if not root:
            return
        #对左子节点,如果符合要求,修改res
        #否则把左子节点设为当前节点,继续递归
        #后面右节点同理
        if root.left:
            if root.left.val == node:
                res[0], res[1] = root.val, depth + 1
            else:
                self.dfs(root.left, node, depth + 1, res)
        if root.right:
            if root.right.val == node:
                res[0], res[1] = root.val, depth + 1
            else:
                self.dfs(root.right, node, depth + 1, res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值