513.找树左下角的值
- 先序遍历
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var depth int
var res int
var maxDep int
func dfs(root *TreeNode) {
if root == nil {
return
}
depth++
// Fist order
if root.Left == nil && root.Right == nil && depth > maxDep{
maxDep = depth
res = root.Val
}
dfs(root.Left)
dfs(root.Right)
depth--
}
func initVar() {
depth = 0
res = 0
maxDep = 0
}
func findBottomLeftValue(root *TreeNode) int {
initVar()
dfs(root)
return res
}
112. 路径总和
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
targetSum -= root.Val
if root.Left == root.Right { // root 是叶子
return targetSum == 0
}
return hasPathSum(root.Left, targetSum) || hasPathSum(root.Right, targetSum)
}
扫描二维码,在手机上阅读
推荐阅读:
收藏