forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin_tree_to_list.py
More file actions
64 lines (50 loc) · 1.53 KB
/
bin_tree_to_list.py
File metadata and controls
64 lines (50 loc) · 1.53 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
56
57
58
59
60
61
62
63
64
"""
Binary Tree to Doubly Linked List
Converts a binary tree to a sorted doubly linked list in-place by
rearranging the left and right pointers of each node.
Reference: https://en.wikipedia.org/wiki/Binary_tree
Complexity:
Time: O(n)
Space: O(n) due to recursion stack
"""
from __future__ import annotations
from algorithms.tree.tree import TreeNode
def bin_tree_to_list(root: TreeNode | None) -> TreeNode | None:
"""Convert a binary tree to a sorted doubly linked list.
Args:
root: The root of the binary tree.
Returns:
The head (leftmost node) of the resulting doubly linked list,
or None if the tree is empty.
Examples:
>>> bin_tree_to_list(None) is None
True
"""
if not root:
return root
root = _bin_tree_to_list_util(root)
while root.left:
root = root.left
return root
def _bin_tree_to_list_util(root: TreeNode | None) -> TreeNode | None:
"""Recursively convert subtree nodes into a doubly linked list.
Args:
root: The root of the subtree to convert.
Returns:
The root of the partially converted subtree.
"""
if not root:
return root
if root.left:
left = _bin_tree_to_list_util(root.left)
while left.right:
left = left.right
left.right = root
root.left = left
if root.right:
right = _bin_tree_to_list_util(root.right)
while right.left:
right = right.left
right.left = root
root.right = right
return root