Contents

993. Cousins in Binary Tree

Problem solution 993 “Cousins in Binary Tree” from LeetCode.


Problem

Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.

Two nodes of a binary tree are cousins if they have the same depth with different parents.

Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.

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

notes:

The number of nodes in the tree is in the range [2, 100]. 1 <= `Node.val`` <= 100 Each node has a unique value. x != y x and y are exist in the tree.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isCousins(root *TreeNode, x int, y int) bool {
    q := [][]*TreeNode{}
    
    if root == nil {
        return true
    }
    if root.Left!=nil && root.Right!=nil {
        if (root.Left.Val == x || root.Left.Val == y) &&
        (root.Right.Val == x || root.Right.Val == y) {
            return false
        }
    }
    q = append(q, []*TreeNode{root.Left, root.Right})
    for k:=0;k<len(q); {
        d := []*TreeNode{}
        c:=0
        
        for idx:=range q[len(q)-1] {
            if q[len(q)-1][idx] == nil {
                continue
            }
            if (q[len(q)-1][idx].Val == x) ||  (q[len(q)-1][idx].Val == y){
                c++
            }
            if c == 2 {
                return true
            }
            r := q[len(q)-1][idx]
            if (r.Left != nil && r.Right!= nil) {
                if (r.Left.Val == x || r.Left.Val == y) &&
                    (r.Right.Val == x || r.Right.Val == y) {
                        return false
                }
            }
            
            if q[len(q)-1][idx].Left != nil {
                d = append(d,q[len(q)-1][idx].Left)
            }
            if q[len(q)-1][idx].Right != nil {
                d = append(d,q[len(q)-1][idx].Right)
            }
        }

        if len(d)>0 {
            q = append(q, d)
        }
        k++
        
    }
    return false
}