[leetcode]树的搜索和回溯算法

这篇博客详细介绍了如何在LeetCode中应用树的搜索和回溯算法,包括二叉搜索树的迭代器、验证序列化、寻找第二小节点等问题,并探讨了回溯算法的dfs模板,如电话号码的字母组合、路径搜索和排列组合。同时讲解了如何解决组合总和、子集和分隔回文串等经典题目,提供了深入的解题思路和代码实现。
摘要由CSDN通过智能技术生成

树的搜索

树的搜索 · SharingSource/LogicStack-LeetCode Wiki (github.com)

173. 二叉搜索树迭代器 (leetcode-cn.com)

image-20211226222309617

其实我就是先中序遍历一遍…(偷懒了)

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)

image-20211226222446440

就是先往左找再往右找边界,如果最后边界刚好是总长就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)

image-20211226223127469

找到一个第二小的点🤣(大小比最开始的点大,比其他点小)

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)

image-20211226223945979

用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})
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值