Skip to content

Commit

Permalink
btree path sum
Browse files Browse the repository at this point in the history
  • Loading branch information
Hoanh An committed Dec 31, 2019
1 parent 5e4addd commit c025f9f
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 105+ Coding Interview Problems with Detailed Solutions
# 106+ Coding Interview Problems with Detailed Solutions

[![Go Report Card](https://goreportcard.com/badge/github.com/hoanhan101/algo)
](https://goreportcard.com/report/github.com/hoanhan101/algo)
Expand Down Expand Up @@ -193,6 +193,8 @@ that you can prepare better for your next coding interviews.
- [Minimum depth](gtci/min_depth_test.go)
- [Maximum depth](gtci/max_depth_test.go)
- [Level order successor](gtci/level_order_successor_test.go)
- Tree depth first search
- [Binary tree path sum](gtci/path_sum_test.go)
- **Other**
- Data structures
- Linked List
Expand Down
80 changes: 80 additions & 0 deletions gtci/path_sum_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
Problem:
- Given a binary tree and a sum, find if the tree has a path from
root-to-leaf such that the sum of all the node values of that path
equals to the sum.
Example:
- Input: sum=8
1
2 3
4 5 6 7
Output: true
Explanation: The path with sum 8 goes through 1, 2 and 5.
- Input: sum=16
1
2 3
4 5 6 7
Output: false
Explanation: There is no path with sum 16.
Approach:
- Traverse the tree in a depth first search fashion.
- At each step, update the new sum by subtracting it with the current
value of the node's we're visiting.
- Once we hit the leaf node, return true if the sum is equal to its
value.
Cost:
- O(n) time, O(n) space.
*/

package gtci

import (
"testing"

"github.com/hoanhan101/algo/common"
)

func TestPathSum(t *testing.T) {
t1 := &common.TreeNode{nil, 1, nil}
t1.Left = &common.TreeNode{nil, 2, nil}
t1.Right = &common.TreeNode{nil, 3, nil}
t1.Left.Left = &common.TreeNode{nil, 4, nil}
t1.Left.Right = &common.TreeNode{nil, 5, nil}
t1.Right.Left = &common.TreeNode{nil, 6, nil}
t1.Right.Right = &common.TreeNode{nil, 7, nil}

tests := []struct {
in1 *common.TreeNode
in2 int
expected bool
}{
{t1, 7, true},
{t1, 8, true},
{t1, 10, true},
{t1, 11, true},
{t1, 16, false},
}

for _, tt := range tests {
common.Equal(
t,
tt.expected,
pathSum(tt.in1, tt.in2),
)
}
}

func pathSum(root *common.TreeNode, sum int) bool {
if root == nil {
return false
}

if root.Value == sum && root.Left == nil && root.Right == nil {
return true
}

return pathSum(root.Left, sum-root.Value) || pathSum(root.Right, sum-root.Value)
}

0 comments on commit c025f9f

Please sign in to comment.