Leetcode Note: Go - Cousins in Binary Tree

Cousins in Binary Tree - LeetCode
https://leetcode.com/problems/cousins-in-binary-tree/

  • Go 言語で取り組んだメモ

回答

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isCousins(root *TreeNode, x int, y int) bool {
    var q []*TreeNode
    
    q = append(q, root)
    for len(q) > 0 {
        res := 0
        shift := len(q)
        for i := 0; i < shift; i++ {
            if q[i] != nil {
                l := q[i].Left
                r := q[i].Right
                // check that only one of childs value is x or y
                if l != nil && (l.Val == x || l.Val == y) {
                    res++
                } else if r != nil && (r.Val == x || r.Val == y) {
                    res++
                }
                q = append(q, l, r)
            }
        }
        if res == 2 {
            return true
        }
		// dequeue current level
        q = q[shift:]
    }
    return false
}