Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 04f83d6

Browse files
committed
count of sub trrees of sum equal to x
1 parent 1eb8a3c commit 04f83d6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
function countOfSubTreeOfX(root, x, countObj) {
9+
if (root == null) return 0;
10+
let sum = root.data + countOfSubTreeOfX(root.leftNode, x, countObj) + countOfSubTreeOfX(root.rightNode, x, countObj);
11+
if (sum == x) countObj.count++;
12+
return sum;
13+
}
14+
//level - 1
15+
let tree = new Node(1);
16+
17+
// level - 2
18+
tree.leftNode = new Node(2);
19+
tree.rightNode = new Node(3);
20+
21+
// level -3
22+
tree.leftNode.leftNode = new Node(4);
23+
tree.leftNode.rightNode = new Node(5);
24+
25+
tree.rightNode.leftNode = new Node(6);
26+
tree.rightNode.rightNode = new Node(2);
27+
28+
// level -4
29+
// tree.leftNode.leftNode.leftNode = new Node(8);
30+
// tree.leftNode.leftNode.rightNode = new Node(9);
31+
32+
// tree.leftNode.rightNode.leftNode = new Node(10);
33+
// tree.leftNode.rightNode.rightNode = new Node(11);
34+
35+
// tree.rightNode.leftNode.leftNode = new Node(12);
36+
// tree.rightNode.leftNode.rightNode = new Node(13);
37+
38+
// tree.rightNode.rightNode.leftNode = new Node(14);
39+
// tree.rightNode.rightNode.rightNode = new Node(15);
40+
// 1
41+
// / \
42+
// 2 3
43+
// / \ / \
44+
// 4 5 6 2
45+
let countObj = { count: 0 };
46+
let x = 11;
47+
countOfSubTreeOfX(tree, x, countObj);
48+
console.log('Total Subtree of ' + x + ' is ' + countObj.count);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /