diff --git a/pkg/questions/construct_binary_tree_from_preorder_and_inorder_traversal/main.go b/pkg/questions/construct_binary_tree_from_preorder_and_inorder_traversal/main.go index 455a460..ee81890 100644 --- a/pkg/questions/construct_binary_tree_from_preorder_and_inorder_traversal/main.go +++ b/pkg/questions/construct_binary_tree_from_preorder_and_inorder_traversal/main.go @@ -43,7 +43,7 @@ func buildTreeInfo(info []NodeInfo) *TreeNode { } } -func buildTree(preorder []int, inorder []int) *TreeNode { +func BuildTree(preorder []int, inorder []int) *TreeNode { info_map := map[int]*NodeInfo{} for o, v := range preorder { info_map[v] = &NodeInfo{ diff --git a/pkg/questions/count_paths_that_can_form_a_palindrome_in_a_tree/main.go b/pkg/questions/count_paths_that_can_form_a_palindrome_in_a_tree/main.go index 906ee96..d55fa2e 100644 --- a/pkg/questions/count_paths_that_can_form_a_palindrome_in_a_tree/main.go +++ b/pkg/questions/count_paths_that_can_form_a_palindrome_in_a_tree/main.go @@ -1,26 +1,53 @@ package count_paths_that_can_form_a_palindrome_in_a_tree -func isPalindromable(s string) bool { - set := map[rune]int{} +type Node struct { + Mask uint64 + Children []*Node +} - for _, b := range s { - set[b]++ +func toTree(parents []int, s string) *Node { + nodes := []*Node{} + for i := range s { + nodes = append(nodes, &Node{1 << (s[i] - 'a'), []*Node{}}) } - singletons := 0 - for _, v := range set { - switch v { - case 1: - singletons++ - case 2: - default: - return false + for child, parent := range parents { + if parent >= 0 { + nodes[parent].Children = append(nodes[parent].Children, nodes[child]) } } - return singletons < 2 + return nodes[0] +} + +func doDFS(node *Node, path uint64, masks map[uint64]int64) { + if node == nil { + return + } + + path ^= node.Mask + + masks[path]++ + for _, child := range node.Children { + doDFS(child, path, masks) + } } func CountPalindromePaths(parent []int, s string) int64 { - return 0 + tree := toTree(parent, s) + + masks := map[uint64]int64{} + doDFS(tree, 0, masks) + + valid := int64(0) + + for mask, count := range masks { + valid += count * (count + 1) / 2 + + for bit := range 26 { + valid += count * masks[mask^(1<