-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree.py
More file actions
55 lines (43 loc) · 1.21 KB
/
binary_tree.py
File metadata and controls
55 lines (43 loc) · 1.21 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
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
"""Returns a string representation of the tree using Preorder Traversal."""
result = []
def preorder(node):
if not node:
return
result.append(str(node.val))
preorder(node.left)
preorder(node.right)
preorder(self)
return " -> ".join(result)
from collections import deque
def create_binary_tree(values):
"""
Creates a binary tree from a level-order list.
Example: [1, 2, 3, None, 4, 5] → Binary Tree
1
/ \
2 3
\ /
4 5
"""
if not values:
return None
root = TreeNode(values[0])
queue = deque([root])
i = 1
while i < len(values):
curr = queue.popleft()
if i < len(values) and values[i] is not None:
curr.left = TreeNode(values[i])
queue.append(curr.left)
i += 1
if i < len(values) and values[i] is not None:
curr.right = TreeNode(values[i])
queue.append(curr.right)
i += 1
return root