[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 {
hash[v] = i
}
root := rebuild(inorder, postorder, len(postorder)-1, 0, len(inorder)-1)
return root
}
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
}