1
1
# Time: O(n)
2
2
# Space: O(h)
3
3
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
+ #
4
53
# Definition for a binary tree node.
5
54
# class TreeNode(object):
6
55
# def __init__(self, x):
@@ -27,7 +76,7 @@ def getHeight(root):
27
76
def preorderTraversal (root , level , left , right , result ):
28
77
if not root :
29
78
return
30
- mid = left + (right - left ) / 2
79
+ mid = left + (right - left )/ 2
31
80
result [level ][mid ] = str (root .val )
32
81
preorderTraversal (root .left , level + 1 , left , mid - 1 , result )
33
82
preorderTraversal (root .right , level + 1 , mid + 1 , right , result )
0 commit comments