树的搜索
树的搜索 · SharingSource/LogicStack-LeetCode Wiki (github.com)
173. 二叉搜索树迭代器 (leetcode-cn.com)
其实我就是先中序遍历一遍…(偷懒了)
type BSTIterator struct {
result []*TreeNode
}
func Constructor(root *TreeNode) BSTIterator {
result := make([]*TreeNode, 0, 100000)
var dfs func(root *TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
dfs(root.Left)
result = append(result, root)
dfs(root.Right)
}
dfs(root)
return BSTIterator{
result: result}
}
func (this *BSTIterator) Next() (ret int) {
ret = this.result[0].Val
this.result = this.result[1:]
return
}
func (this *BSTIterator) HasNext() bool {
return len(this.result) > 0
}
331. 验证二叉树的前序序列化 (leetcode-cn.com)
就是先往左找再往右找边界,如果最后边界刚好是总长就ok
//获取边界的终点
func isOK(nums []string, index int) int {
if index >= len(nums) || index == -1 {
return -1
}
if nums[index] == "#" {
//遇到终止就返回下一个起始点
return index + 1
}
return isOK(nums, isOK(nums, index+1))
}
func isValidSerialization(preorder string) bool {
nums := strings.Split(preorder, ",")
return isOK(nums, 0) == len(nums) //看看整个的终点是不是刚好是总长度
}
671. 二叉树中第二小的节点 - 力扣(LeetCode) (leetcode-cn.com)
找到一个第二小的点🤣(大小比最开始的点大,比其他点小)
func findSecondMinimumValue(root *TreeNode) int {
ans := -1
rootVal := root.Val
var dfs func(*TreeNode)
dfs = func(node *TreeNode) {
if node == nil || ans != -1 && node.Val >= ans {
return
}
if node.Val > rootVal {
ans = node.Val
}
dfs(node.Left)
dfs(node.Right)
}
dfs(root)
return ans
}
993. 二叉树的堂兄弟节点 (leetcode-cn.com)
用bfs即可
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Node struct{
parent *TreeNode
node *TreeNode
level int
}
func isCousins(root *TreeNode, x int, y int) bool {
queue := make([]*Node,0,101)
queue = append(queue,&Node{
parent:nil,node:root,level:0})
isOk := 0
var x1,y1 *Node
for len(queue)>0 {
p := queue[0]
queue = queue[1:]
if p.node.Val == x{
x1 = p
isOk++
}
if p.node.Val == y{
y1 = p
isOk++
}
if isOk == 2{
break
}
if p.node.Left!=nil{
queue = append(queue,&Node{
parent:p.node,node:p.node.Left,level:p.level+1})
}