Problem statement

https://binarysearch.com/problems/Sibling-Tree-Value/

Solution

Use dfs with parent node.

Complexity

It is O(n) for time and O(h) for space.

Code

class Solution:
    def solve(self, root, k):
        def dfs(node, par, val):
            if not node: return
            if node.val == val: return par
            return dfs(node.left, node, val) or dfs(node.right, node, val)
        p = dfs(root, None, k)
        return p.left.val if p.left.val != k else p.right.val