This commit is contained in:
2026-06-25 23:08:12 +10:00
parent 5c25a2e856
commit 416b0e9954
2 changed files with 116 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
package top100liked
// https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/?envType=study-plan-v2&envId=top-100-liked
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// func buildTree(preorder []int, inorder []int) *TreeNode {
// if len(preorder) == 0 {
// return nil
// }
// if len(preorder) == 1 {
// return &TreeNode{Val: preorder[0]}
// }
// rootVal := preorder[0]
// root := &TreeNode{Val: rootVal}
// for i, v := range inorder {
// if v == rootVal {
// root.Left = buildTree(preorder[1:1+i], inorder[:i])
// root.Right = buildTree(preorder[1+i:], inorder[i+1:])
// break
// }
// }
// return root
// }
func buildTree(preorder, inorder []int) *TreeNode {
idx := map[int]int{}
for i, v := range inorder {
idx[v] = i
}
var dfs func(preL, preR, inL, inR int) *TreeNode
dfs = func(preL, preR, inL, inR int) *TreeNode {
if preL > preR {
return nil
}
rootVal := preorder[preL]
mid := idx[rootVal]
leftSize := mid - inL
return &TreeNode{
Val: rootVal,
Left: dfs(preL+1, preL+leftSize, inL, mid-1),
Right: dfs(preL+leftSize+1, preR, mid+1, inR),
}
}
return dfs(0, len(preorder)-1, 0, len(inorder)-1)
}
+66
View File
@@ -0,0 +1,66 @@
package top100liked
import (
"fmt"
"testing"
)
// https://leetcode.cn/problems/path-sum-iii/description/?envType=study-plan-v2&envId=top-100-liked
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 朴素解法,可以AC,但时间复杂度高
// func pathSum(root *TreeNode, targetSum int) int {
// if root == nil {
// return 0
// }
// res := countFrom(root, targetSum)
// res += pathSum(root.Left, targetSum)
// res += pathSum(root.Right, targetSum)
// return res
// }
// func countFrom(node *TreeNode, target int) int {
// if node == nil {
// return 0
// }
// c := 0
// if node.Val == target {
// c++
// }
// c += countFrom(node.Left, target-node.Val)
// c += countFrom(node.Right, target-node.Val)
// return c
// }
// 前缀和
func pathSum(root *TreeNode, targetSum int) int {
m := make(map[int]int)
count := 0
m[0] = 1
var dfs func(*TreeNode, int)
dfs = func(root *TreeNode, cur int) {
if root == nil {
return
}
cur += root.Val
count += m[cur-targetSum]
m[cur]++
dfs(root.Left, cur)
dfs(root.Right, cur)
m[cur]--
}
dfs(root, 0)
return count
}
func Test(t *testing.T) {
input := &TreeNode{
Val: 1,
Right: &TreeNode{Val: 2, Right: &TreeNode{Val: 3, Right: &TreeNode{Val: 4, Right: &TreeNode{Val: 5}}}},
}
fmt.Println(pathSum(input, 3) == 2)
}