前言
都是递归和迭代,看着很简单,还是写不出来,理解还是不够。。。
内容
一、左叶子之和
给定二叉树的根节点 root
,返回所有左叶子之和。
递归
func sumOfLeftLeaves(root *TreeNode) int {
if root==nil{
return 0
}
left:=sumOfLeftLeaves(root.Left)
if root.Left!=nil&&root.Left.Left==nil&&root.Left.Right==nil{
left=root.Left.Val
}
right:=sumOfLeftLeaves(root.Right)
return left+right
}
二、找树左下角的值
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
深度优先搜索
var depth int
var result int
func findBottomLeftValue(root *TreeNode) int {
depth,result=0,0
dfs(root,1)
return result
}
func dfs(root *TreeNode,d int){
if root==nil{
return
}
if root.Left==nil&&root.Right==nil&&depth<d{
depth=d
result=root.Val
}
dfs(root.Left,d+1)
dfs(root.Right,d+1)
}
广度优先搜索
func findBottomLeftValue(root *TreeNode)int{
var ans int
queue:=[]*TreeNode{root}
for len(queue)>0{
node:=queue[0]
queue=queue[1:]
if node.Right!=nil{
queue=append(queue,node.Right)
}
if node.Left!=nil{
queue=append(queue,node.Left)
}
ans=node.Val
}
return ans
}
理解误区
理解有误,晚上看视频才知道。最底层最左边,不一定非得是左子树。比如下图,输出为5
最后
心思不在写题上。。。