Leetcode - String Compression
Leetcode - Design Compressed String Iterator

Leetcode - Cousins in Binary Tree

violet posted @ May 08, 2020 02:25:40 AM in 算法 with tags Algorithm tree Golang , 211 阅读

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:

  1. The number of nodes in the tree will be between 2 and 100.
  2. Each node has a unique integer value from 1 to 100.
/**
 * 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
}
Anamika SHukla 说:
May 29, 2021 08:00:29 PM

All the Important Information has been shared here.
http://www.sonalisharma.co.in/

Escorts in Dehradun 说:
Sep 22, 2021 02:21:08 PM

Your site does not respond ! what nice blog.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter