-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRootToLeafSum.cs
More file actions
62 lines (50 loc) · 1.85 KB
/
RootToLeafSum.cs
File metadata and controls
62 lines (50 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructures.Libraries.Trees
{
[TestClass]
public class RootToLeafSum
{
public bool FindRootToLeafSumPath(BinaryTreeNode root, double sum, List<double> result)
{
// check if it's leaf node
if (root.Left == null && root.Right == null)
{
bool isTarget = false;
if (sum == root.Value)
{
isTarget = true;
result.Add(root.Value);
}
return isTarget;
}
bool isTargetSumLeft = this.FindRootToLeafSumPath(root.Left, sum - root.Value, result);
bool isTargetSumRight = this.FindRootToLeafSumPath(root.Right, sum - root.Value, result);
if (isTargetSumLeft) result.Add(root.Value);
if (isTargetSumRight) result.Add(root.Value);
return isTargetSumLeft || isTargetSumRight;
}
[TestMethod]
public void TestFindRootToLeaftSumPath()
{
/// 20
/// / \
/// 10 30
/// / \ / \
/// 5 12 25 35
var root = new BinaryTreeNode(20);
root.Left = new BinaryTreeNode(10);
root.Right = new BinaryTreeNode(30);
root.Left.Left = new BinaryTreeNode(5);
root.Left.Right = new BinaryTreeNode(12);
root.Right.Left = new BinaryTreeNode(25);
root.Right.Right = new BinaryTreeNode(35);
List<double> listArray = new List<double>();
bool isTargetExist = this.FindRootToLeafSumPath(root, 80, listArray);
}
}
}