代码随想录算法训练营第十八天|[513].找树左下角的值、[112].路径总和、[106].从中序与后序遍历序列构造二叉树

[513].找树左下角的值

func findBottomLeftValue(root *TreeNode) int {
	var gradation int
	queue := list.New()

	queue.PushBack(root)
	for queue.Len()>0{
		length:= queue.Len()
		for i := 0; i < length; i++ {
			node:=queue.Remove(queue.Front()).(*TreeNode)
			if i==0{
				gradation = node.Val
			}
			if node.Left !=nil{
				queue.PushBack(node.Left)
			}
			if node.Right !=nil{
				queue.PushBack(node.Right)
			}
			
		}
	}
	return gradation

}

[513].找树左下角的值

 var depth int
 var res int
func findBottomLeftValue(root *TreeNode) int {
	depth,res = 0,0
	dfs(root,1)
	return res
}

func dfs(root *TreeNode,d int){
	if root == nil{
		return 
	}
	if root.Left == nil && root.Right == nil && depth < 0{
		depth = d 
		res = root.Val
	}

	dfs(root.Left,d+1)
	dfs(root.Right,d+1)
}

[112].路径总和

func hasPathSum(root *TreeNode, targetSum int) bool {
	if root==nil{
		return false
	}
	targetSum -= root.Val
	if root.Left==nil&&root.Right==nil&&targetSum==0{
		return true
	}
	return hasPathSum(root.Left,targetSum)||hasPathSum(root.Right,targetSum)
	

}

[106].从中序与后序遍历序列构造二叉树

var (
    hash map[int]int
)
func buildTree(inorder []int, postorder []int) *TreeNode {
    hash = make(map[int]int)
    for i, v := range inorder {  // 用map保存中序序列的数值对应位置
        hash[v] = i
    }
    // 以左闭右闭的原则进行切分
    root := rebuild(inorder, postorder, len(postorder)-1, 0, len(inorder)-1)
    return root
}
// rootIdx表示根节点在后序数组中的索引,l, r 表示在中序数组中的前后切分点
func rebuild(inorder []int, postorder []int, rootIdx int, l, r int) *TreeNode {
    if l > r {    // 说明没有元素,返回空树
        return nil
    }
    if l == r {  // 只剩唯一一个元素,直接返回
        return &TreeNode{Val : inorder[l]}
    }
    rootV := postorder[rootIdx]  // 根据后序数组找到根节点的值
    rootIn := hash[rootV]        // 找到根节点在对应的中序数组中的位置
    root := &TreeNode{Val : rootV}   // 构造根节点
    // 重建左节点和右节点
    root.Left = rebuild(inorder, postorder, rootIdx-(r-rootIn)-1, l, rootIn-1)
    root.Right = rebuild(inorder, postorder, rootIdx-1, rootIn+1, r)
    return root
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值