Skip to content

Commit 106eb15

Browse files
committed
Flatten_binary_tree
1 parent a962b6e commit 106eb15

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
"""
2+
Flatten a binary tree to a linked list in-place.
3+
4+
The algorithm modifies the given binary tree so that it becomes a right-skewed
5+
linked list following preorder traversal order (root -> left -> right).
6+
7+
Time complexity: O(n)
8+
Space complexity: O(1) (excluding recursion stack)
9+
10+
Doctest:
11+
>>> # build tree: [1,2,5,3,4,None,6]
12+
>>> root = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(5, None, TreeNode(6)))
13+
>>> flatten(root)
14+
>>> to_list(root)
15+
[1, 2, 3, 4, 5, 6]
16+
17+
>>> # single node
18+
>>> root = TreeNode(0)
19+
>>> flatten(root)
20+
>>> to_list(root)
21+
[0]
22+
"""
23+
24+
from __future__ import annotations
25+
from typing import Optional, List
26+
import doctest
27+
28+
29+
class TreeNode:
30+
"""
31+
Node of a binary tree.
32+
33+
Attributes:
34+
val (int): Node value.
35+
left (Optional[TreeNode]): Left child.
36+
right (Optional[TreeNode]): Right child.
37+
"""
38+
39+
def __init__(
40+
self,
41+
val: int = 0,
42+
left: Optional["TreeNode"] = None,
43+
right: Optional["TreeNode"] = None,
44+
) -> None:
45+
self.val = val
46+
self.left = left
47+
self.right = right
48+
49+
50+
def flatten(root: Optional[TreeNode]) -> None:
51+
"""
52+
Flatten the binary tree rooted at `root` into a right-skewed linked list
53+
following preorder traversal. Modifies the tree in-place.
54+
55+
Args:
56+
root (Optional[TreeNode]]): Root of the binary tree.
57+
58+
Returns:
59+
None
60+
"""
61+
current = root
62+
while current:
63+
if current.left:
64+
# Find rightmost node of left subtree (predecessor)
65+
predecessor = current.left
66+
while predecessor.right:
67+
predecessor = predecessor.right
68+
69+
# Move current.right after predecessor
70+
predecessor.right = current.right
71+
# Make left subtree the new right subtree
72+
current.right = current.left
73+
current.left = None
74+
current = current.right
75+
76+
77+
def to_list(root: Optional[TreeNode]) -> List[int]:
78+
"""
79+
Helper to collect values from the flattened tree following right pointers.
80+
81+
Args:
82+
root (Optional[TreeNode]): Root of the (flattened) tree.
83+
84+
Returns:
85+
List[int]: Values in order along right pointers.
86+
"""
87+
result: List[int] = []
88+
node = root
89+
while node:
90+
result.append(node.val)
91+
node = node.right
92+
return result
93+
94+
95+
if __name__ == "__main__":
96+
# Run doctests when executed as a script.
97+
# This is intended for local checks only. Formal tests should go in tests/.
98+
failures, tests = doctest.testmod(report=False)
99+
if failures:
100+
print(f"Doctest failures: {failures} out of {tests} tests.")
101+
else:
102+
print(f"All {tests} doctests passed.")

knapsack/test_flatten_binary_tree.py

Whitespace-only changes.

0 commit comments

Comments
 (0)