In a binary tree, two nodes are considered siblings if they both have the same parent node. Given a binary tree and two node values, x and y, write a program to determine if these two nodes are siblings. If the nodes have the same parent, return True, otherwise, return False.
Input: Binary Tree =[1,2,3,null,null,4,5], x =2, y =5Output: False
Explanation: Nodes 2 and 5 are not siblings because they do not share the same parent.
classSolution:
defareSiblings(self, root: TreeNode, x: int, y: int) -> bool:
# Base case: if root is None, return Falseifnot root:
returnFalse# Check if the current node's children are x and yif root.left and root.right:
if (root.left.val == x and root.right.val == y) or \
(root.left.val == y and root.right.val == x):
returnTrue# Recursively search in left and right subtreesreturn self.areSiblings(root.left, x, y) or self.areSiblings(root.right, x, y)
# Example usage:# Tree: 1 -> [2, 3], 3 -> [4, 5]root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
solution = Solution()
print(solution.areSiblings(root, 4, 5)) # Output: Trueprint(solution.areSiblings(root, 2, 5)) # Output: False