Golang leetcode 513. Find Bottom Left Tree Value.go

时间:2022-06-19
本文章向大家介绍Golang leetcode 513. Find Bottom Left Tree Value.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89175648

思路

深度优先搜索整个树,记录层数 每次搜索的时候,第一个碰到的元素,就是该层的最左子树

code

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}
var maxd, val int

func findBottomLeftValue(root *TreeNode) int {
	maxd = 0
	val = 0
	dfs(root, 1)
	return val
}

func dfs(root *TreeNode, d int) {
	if root == nil {
		return
	}
	if d > maxd {
		maxd = d
		val = root.Val
	}
	if root.Left != nil {
		dfs(root.Left, d+1)
	}
	if root.Right != nil {
		dfs(root.Right, d+1)
	}

}