My LeetCode grinding. Trying to do a problem a day.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

main.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Definition for a binary tree node.
  2. class TreeNode:
  3. def __init__(self, val=0, left=None, right=None):
  4. self.val = val
  5. self.left = left
  6. self.right = right
  7. class Solution:
  8. def __init__(self):
  9. self.xPar = None
  10. self.xDepth = None
  11. self.yPar = None
  12. self.yDepth = None
  13. def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
  14. # descend the binary tree and find the two values, set their parents
  15. # exit and then compare
  16. # because ints are unique and the nodes do exist there
  17. # shouldn't be too many edge cases I don't think
  18. self.descendTreeFinding(root, x, y, None, 0)
  19. return self.xDepth == self.yDepth and self.xPar != self.yPar
  20. def descendTreeFinding(self, tree, x, y, parent, depth):
  21. if tree is None:
  22. return
  23. if tree.val == x:
  24. self.xPar = parent
  25. self.xDepth = depth
  26. if tree.val == y:
  27. self.yPar = parent
  28. self.yDepth = depth
  29. if self.yPar is not None and self.xPar is not None:
  30. return
  31. else:
  32. self.descendTreeFinding(tree.left, x, y, tree.val, depth + 1)
  33. self.descendTreeFinding(tree.right, x, y, tree.val, depth + 1)
  34. s = Solution()
  35. print("Expected: true")
  36. tree = TreeNode(1)
  37. left = TreeNode(2)
  38. left.right = TreeNode(4)
  39. tree.left = left
  40. right = TreeNode(3)
  41. right.right = TreeNode(5)
  42. tree.right = right
  43. print("Got:", s.isCousins(tree, 4, 5))