Masalalar
Go Algoritm masala

Daraxt “Binary Search Tree”mi?

28 September, 2026
Go
package main

// type TreeNode struct { 
//    Val   int
//    Left  *TreeNode
//    Right *TreeNode
// }        

import "math"

func (_ Solution) IsValidBST(root *TreeNode) bool {
  if root == nil {
    return true 
  }

  type Item struct {
    node *TreeNode
    min int64
    max int64
  }

  queue := []Item{
    {
      node: root,
      min: math.MinInt64,
      max: math.MaxInt64,
    },
  }

  for len(queue) > 0 {
    current := queue[0]
    queue = queue[1:]

    node := current.node

    if int64(node.Val) <= current.min || int64(node.Val) >= current.max {
      return false
    }

    if node.Left != nil {
      queue = append(queue, Item{
        node: node.Left,
        min: current.min,
        max: int64(node.Val),
      })
    }
    
    if node.Right != nil {
      queue = append(queue, Item{
        node: node.Right,
        min: int64(node.Val),
        max: current.max,
      })
    }
  }
  return true 
}

videoni ko'ring

👍 0 ❤️ 1 🔥 0

Izohlar 0

Izoh qoldirish uchun kiring yoki ro'yxatdan o'ting.

Hali izoh yo'q. Birinchi bo'ling!