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 20428ab

Browse files
author
Manjunath
committed
sum of vertical line in BT
1 parent bb2c65c commit 20428ab

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
9+
class DLList {
10+
constructor(data) {
11+
this.data = data;
12+
this.next = this.prev = null;
13+
}
14+
}
15+
16+
function verticalLineSum(root, doublyList) {
17+
if (root == null) return;
18+
doublyList.data = doublyList.data + root.data;
19+
if (root.leftNode) {
20+
if (doublyList.prev == null) {
21+
let tempNode = new DLList(0)
22+
doublyList.prev = tempNode;
23+
tempNode.next = doublyList;
24+
}
25+
verticalLineSum(root.leftNode, doublyList.prev);
26+
}
27+
if (root.rightNode) {
28+
if (doublyList.next == null) {
29+
let tempNode = new DLList(0)
30+
doublyList.next = tempNode;
31+
tempNode.prev = doublyList;
32+
}
33+
verticalLineSum(root.rightNode, doublyList.next);
34+
}
35+
}
36+
37+
function displayList(list) {
38+
let count = 1;
39+
while (list != null) {
40+
console.log('Line ' + count + ' sum -> ' + list.data + ' ');
41+
list = list.next;
42+
count++;
43+
}
44+
}
45+
46+
//level - 1
47+
let tree = new Node(1);
48+
49+
// level - 2
50+
tree.leftNode = new Node(2);
51+
tree.rightNode = new Node(3);
52+
53+
// level -3
54+
tree.leftNode.leftNode = new Node(4);
55+
tree.leftNode.rightNode = new Node(5);
56+
57+
tree.rightNode.leftNode = new Node(6);
58+
tree.rightNode.rightNode = new Node(7);
59+
60+
// level -4
61+
tree.leftNode.leftNode.leftNode = new Node(8);
62+
tree.leftNode.leftNode.rightNode = new Node(9);
63+
64+
tree.leftNode.rightNode.leftNode = new Node(10);
65+
tree.leftNode.rightNode.rightNode = new Node(11);
66+
67+
tree.rightNode.leftNode.leftNode = new Node(12);
68+
tree.rightNode.leftNode.rightNode = new Node(13);
69+
70+
tree.rightNode.rightNode.leftNode = new Node(14);
71+
tree.rightNode.rightNode.rightNode = new Node(15);
72+
// 1
73+
// / \
74+
// 2 3
75+
// / \ / \
76+
// 4 5 6 7
77+
// / \ / \ / \ / \
78+
// 8 9 10 11 12 13 14 15
79+
let doublyList = new DLList(0);
80+
verticalLineSum(tree, doublyList);
81+
while (doublyList.prev != null)
82+
doublyList = doublyList.prev;
83+
displayList(doublyList);

0 commit comments

Comments
(0)

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