【leetcode】993. Cousins in Binary Tree

亦凉 2022-01-07 11:27 247阅读 0赞

题目如下:

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:
q1248-01.png

  1. Input: root = [1,2,3,4], x = 4, y = 3
  2. Output: false

Example 2:
q1248-02.png

  1. Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
  2. Output: true

Example 3:

q1248-03.png

  1. Input: root = [1,2,3,null,4], x = 2, y = 3
  2. Output: false

Note:

  1. The number of nodes in the tree will be between 2 and 100.
  2. Each node has a unique integer value from 1 to 100.

解题思路:遍历树,找到对应X和Y的节点,并记录其level和parent即可。

代码如下:

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. x_p = None
  9. y_p = None
  10. x_l = 0
  11. y_l = 0
  12. def recursive(self,node,level,parent,x,y):
  13. if node.val == x:
  14. self.x_p = parent
  15. self.x_l = level
  16. elif node.val == y:
  17. self.y_p = parent
  18. self.y_l = level
  19. if node.left != None:
  20. self.recursive(node.left,level+1,node,x,y)
  21. if node.right != None:
  22. self.recursive(node.right, level + 1, node, x, y)
  23. def isCousins(self, root, x, y):
  24. """
  25. :type root: TreeNode
  26. :type x: int
  27. :type y: int
  28. :rtype: bool
  29. """
  30. self.x_p = None
  31. self.y_p = None
  32. self.x_l = 0
  33. self.y_l = 0
  34. self.recursive(root,0,None,x,y)
  35. return self.x_p != self.y_p and self.x_l == self.y_l

转载于:https://www.cnblogs.com/seyjs/p/10410669.html

发表评论

表情:
评论列表 (有 0 条评论,247人围观)

还没有评论,来说两句吧...

相关阅读