Skip to content

Commit c2878b2

Browse files
authored
Create BINARY TREE (#3546)
2 parents 16a7dc5 + e5dd242 commit c2878b2

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

BINARY TREE

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Diagonal Sum in Binary Tree
2+
# Addresses #3016
3+
4+
from collections import deque, defaultdict
5+
6+
# Definition for a binary tree node.
7+
class Node:
8+
def __init__(self, data):
9+
self.data = data
10+
self.left = None
11+
self.right = None
12+
13+
14+
def diagonalSum(root):
15+
"""
16+
Function to calculate the diagonal sum of a binary tree.
17+
Each diagonal is considered from top-right to bottom-left.
18+
19+
Args:
20+
root (Node): Root node of the binary tree.
21+
22+
Returns:
23+
List[int]: List containing sum of each diagonal.
24+
"""
25+
if not root:
26+
return []
27+
28+
q = deque([(root, 0)]) # (node, diagonal_index)
29+
diag_sums = defaultdict(int)
30+
31+
while q:
32+
node, d = q.popleft()
33+
diag_sums[d] += node.data
34+
35+
# Left child goes to next diagonal
36+
if node.left:
37+
q.append((node.left, d + 1))
38+
39+
# Right child stays on the same diagonal
40+
if node.right:
41+
q.append((node.right, d))
42+
43+
# Return sums in order of diagonals
44+
return [diag_sums[i] for i in sorted(diag_sums.keys())]
45+
46+
47+
# -----------------------
48+
# Example test case below
49+
# -----------------------
50+
if __name__ == "__main__":
51+
"""
52+
8
53+
/ \
54+
3 10
55+
/ \ \
56+
1 6 14
57+
/ \ /
58+
4 7 13
59+
Expected Output: [32, 29, 5]
60+
Explanation:
61+
Diagonals:
62+
D0: [8, 10, 14] = 32
63+
D1: [3, 6, 7, 13] = 29
64+
D2: [1, 4] = 5
65+
"""
66+
root = Node(8)
67+
root.left = Node(3)
68+
root.right = Node(10)
69+
root.left.left = Node(1)
70+
root.left.right = Node(6)
71+
root.left.right.left = Node(4)
72+
root.left.right.right = Node(7)
73+
root.right.right = Node(14)
74+
root.right.right.left = Node(13)
75+
76+
print(diagonalSum(root))

0 commit comments

Comments
 (0)