-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathRootToLeaf.cs
More file actions
101 lines (80 loc) · 2.7 KB
/
PathRootToLeaf.cs
File metadata and controls
101 lines (80 loc) · 2.7 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using DataStructures.Libraries.Trees;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Problem.BinaryTree
{
[TestClass]
public class PathRootToLeaf
{
public PathRootToLeaf()
{
}
public bool PathToSpecificNode(BinaryTreeNode root, BinaryTreeNode node, List<double> array)
{
if (root == null) return false;
if (root == node)
{
array.Add(root.Value);
return true;
}
if (this.PathToSpecificNode(root.Left, node, array) ||
this.PathToSpecificNode(root.Right, node, array))
{
array.Add(root.Value);
return true;
}
return false;
}
public void PathRootToLeafImpl(BinaryTreeNode root)
{
double[] path = new double[100];
this.PathRootToLeafImpl(root, 0, path);
}
public void PathRootToLeafImpl(BinaryTreeNode root, int counter, double[] path)
{
if (root == null) return;
path[counter++] = root.Value;
// Leaf node
if (root.Left == null && root.Right == null)
{
for (int i = 0; i < counter; i++)
{
Console.Write(path[i] + " ");
}
Console.WriteLine();
}
else
{
PathRootToLeafImpl(root.Left, counter, path);
PathRootToLeafImpl(root.Right, counter, path);
}
}
[TestMethod]
public void ValidateTreePathToLeaf()
{
var binarySearchTree = new BinarySearchTree();
binarySearchTree.PopulateDefaultBalanceTree();
var pathRootToLeaf = new PathRootToLeaf();
pathRootToLeaf.PathRootToLeafImpl(binarySearchTree.Root);
}
[TestMethod]
public void TestPathToSpecificNode()
{
BinaryTreeNode root = new BinaryTreeNode(5);
root.Left = new BinaryTreeNode(10);
root.Right = new BinaryTreeNode(15);
root.Left.Left = new BinaryTreeNode(20);
root.Left.Right = new BinaryTreeNode(25);
root.Right.Left = new BinaryTreeNode(30);
root.Right.Right = new BinaryTreeNode(35);
root.Left.Right.Right = new BinaryTreeNode(45);
BinaryTreeNode node = root.Left.Right.Right;
List<double> array = new List<double>();
this.PathToSpecificNode(root, node, array);
}
}
}