Leetcode - Cousins in Binary Tree
https://leetcode.com/problems/cousins-in-binary-tree/
In a binary tree, the root node is at depth 0
, and children of each depth k
node are at depth k+1
.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root
of a binary tree with unique values, and the values x
and y
of two different nodes in the tree.
Return true
if and only if the nodes corresponding to the values x
and y
are cousins.
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
Note:
-
The number of nodes in the tree will be between
2
and100
. -
Each node has a unique integer value from
1
to100
.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isCousins(root *TreeNode, x int, y int) bool { queue := []*TreeNode{root} foundX := false foundY := false for len(queue) != 0 { size := len(queue) foundX = false foundY = false for i := 0; i < size; i++ { node := queue[i] if node.Left != nil && node.Right != nil { if (node.Left.Val == x && node.Right.Val == y) || (node.Left.Val == y && node.Right.Val == x) { return false } } if node.Left != nil { if node.Left.Val == x { foundX = true } if node.Left.Val == y { foundY = true } queue = append(queue, node.Left) } if node.Right != nil { if node.Right.Val == x { foundX = true } if node.Right.Val == y { foundY = true } queue = append(queue, node.Right) } } queue = queue[size:] if foundX && foundY { return true } } return foundX && foundY }
May 29, 2021 08:00:29 PM
All the Important Information has been shared here.
http://www.sonalisharma.co.in/
Sep 22, 2021 02:21:08 PM
Your site does not respond ! what nice blog.