这是我参与更文挑战的第25天,活动详情查看: 更文挑战
描述
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
Note:
The number of nodes in the tree will be between 2 and 100.
Each node has a unique integer value from 1 to 100
解析
根据题意,就是将判断 x 和 y 是不是堂兄弟关系,这种关系就是两个节点都在树的同一深度下,并且父节点不同即可。使用 DFS 进行递归操作,用字典 d 记录每一层的节点列表,用 r 记录 x 和 y 的父节点,如果 x 和 y 在同一个层的列表中,然后其父节点不同即可返回 True。
解答
# 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
"""
d = {}
r = {}
def isCousin(root, parent, count):
if not root:
return
if count not in d:
d[count] = []
d[count].append(root.val)
if (root.val == x or root.val == y) and parent:
r[root.val] = parent.val
if x in d[count] and y in d[count] and r[x] != r[y]:
return True
return isCousin(root.left, root, count + 1) or isCousin(root.right, root, count + 1)
return isCousin(root, None, 0)
运行结果
Runtime: 20 ms, faster than 67.64% of Python online submissions for Cousins in Binary Tree.
Memory Usage: 13.6 MB, less than 35.54% of Python online submissions for Cousins in Binary Tree.
解析
看其他高手,直接在进行 DFS 的时候,直接将 x 和 y 的深度和父节点都记录下来,运行函数之后直接对结果进行判断即可。
解答
# 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
"""
res = []
def dfs(node, parent, depth):
if not node:
return
if node.val == x or node.val == y:
res.append((parent, depth))
dfs(node.left, node, depth + 1)
dfs(node.right, node, depth + 1)
dfs(root, None, 0)
node_x, node_y = res
return node_x[0] != node_y[0] and node_x[1] == node_y[1]
运行结果
Runtime: 20 ms, faster than 67.64% of Python online submissions for Cousins in Binary Tree.
Memory Usage: 13.4 MB, less than 63.66% of Python online submissions for Cousins in Binary Tree.
原题链接:leetcode.com/problems/co…
您的支持是我最大的动力