Skip to content

Commit b198237

Browse files
authored
Update print-binary-tree.py
1 parent f0505f2 commit b198237

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

Python/print-binary-tree.py

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,55 @@
11
# Time: O(n)
22
# Space: O(h)
33

4+
# Print a binary tree in an m*n 2D string array following these rules:
5+
#
6+
# The row number m should be equal to the height of the given binary tree.
7+
# The column number n should always be an odd number.
8+
# The root node's value (in string format) should be put in the exactly middle of the first row it can be put.
9+
# The column and the row where the root node belongs will separate the rest space into two parts
10+
# (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and
11+
# print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size.
12+
# Even if one subtree is none while the other is not, you don't need to print anything for the none subtree
13+
# but still need to leave the space as large as that for the other subtree. However, if two subtrees are none,
14+
# then you don't need to leave space for both of them.
15+
# Each unused space should contain an empty string "".
16+
# Print the subtrees following the same rules.
17+
# Example 1:
18+
# Input:
19+
# 1
20+
# /
21+
# 2
22+
# Output:
23+
# [["", "1", ""],
24+
# ["2", "", ""]]
25+
# Example 2:
26+
# Input:
27+
# 1
28+
# / \
29+
# 2 3
30+
# \
31+
# 4
32+
# Output:
33+
# [["", "", "", "1", "", "", ""],
34+
# ["", "2", "", "", "", "3", ""],
35+
# ["", "", "4", "", "", "", ""]]
36+
# Example 3:
37+
# Input:
38+
# 1
39+
# / \
40+
# 2 5
41+
# /
42+
# 3
43+
# /
44+
# 4
45+
# Output:
46+
#
47+
# [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
48+
# ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]
49+
# ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
50+
# ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]
51+
# Note: The height of binary tree is in the range of [1, 10].
52+
#
453
# Definition for a binary tree node.
554
# class TreeNode(object):
655
# def __init__(self, x):
@@ -27,7 +76,7 @@ def getHeight(root):
2776
def preorderTraversal(root, level, left, right, result):
2877
if not root:
2978
return
30-
mid = left + (right - left) / 2
79+
mid = left + (right-left)/2
3180
result[level][mid] = str(root.val)
3281
preorderTraversal(root.left, level+1, left, mid-1, result)
3382
preorderTraversal(root.right, level+1, mid+1, right, result)

0 commit comments

Comments
 (0)