Day18 二叉树 Part05
513. 找树左下角的值 - 力扣(LeetCode)
用层序遍历,感觉简单易懂些,也可以用其他遍历方法,只要考虑好高度就可以了
func findBottomLeftValue(root *TreeNode) (ans int) {
q := []*TreeNode{root}
for len(q) > 0 {
node := q[0]
q = q[1:]
if node.Right != nil {
q = append(q, node.Right)
}
if node.Left != nil {
q = append(q, node.Left)
}
ans = node.Val
}
return
}
112. 路径总和 - 力扣(LeetCode)
尽量写的比较简洁了
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
} else {
targetSum -= root.Val
if root.Left == nil && root.Right == nil && targetSum == 0 {
return true
}
}
return hasPathSum(root.Left, targetSum) || hasPathSum(root.Right, targetSum)
}
以前也写过一版,用的层序遍历来着
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
queNode := []*TreeNode{}
queVal := []int{}
queNode = append(queNode, root)
queVal = append(queVal, root.Val)
for len(queNode) != 0 {
now := queNode[0]
queNode = queNode[1:]
temp := queVal[0]
queVal = queVal[1:]
if now.Left == nil && now.Right == nil {
if temp == targetSum {
return true
}
continue
}
if now.Left != nil {
queNode = append(queNode, now.Left)
queVal = append(queVal, now.Left.Val + temp)
}
if now.Right != nil {
queNode = append(queNode, now.Right)
queVal = append(queVal, now.Right.Val + temp)
}
}
return false
}
106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
见一次怕一次emmmmm
重点在于用map存储中序遍历,这个应该算个关键
func buildTree(inorder []int, postorder []int) *TreeNode {
idxMap := map[int]int{} // 存储中序序列
for i, v := range inorder {
idxMap[v] = i
}
var build func(int, int) *TreeNode
build = func(inorderLeft, inorderRight int) *TreeNode { // left right 分别代表左右边界
if inorderLeft > inorderRight { // 左边界大于右边界,返回空节点
return nil
}
val := postorder[len(postorder)-1]
postorder = postorder[:len(postorder)-1] // 选最后一个节点作为根节点
root := &TreeNode{Val: val}
inorderRootIndex := idxMap[val] // 利用哈希找出左右节点的位置
root.Right = build(inorderRootIndex+1, inorderRight)
root.Left = build(inorderLeft, inorderRootIndex-1)
return root
}
return build(0, len(inorder)-1)
}