-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path655.print-binary-tree.py
35 lines (30 loc) · 1020 Bytes
/
655.print-binary-tree.py
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
#
# @lc app=leetcode id=655 lang=python3
#
# [655] Print Binary Tree
#
# @lc code=start
# TAGS: Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# 28 ms, 92.33%. Time: O(N). Space: O(H)
def printTree(self, root: TreeNode) -> List[List[str]]:
def get_depth(node):
if not node: return 0
return max(get_depth(node.left), get_depth(node.right)) + 1
def insert_value(node, lo, hi, depth=0):
if not node: return
mid = (lo + hi) // 2
output[depth][mid] = str(node.val)
insert_value(node.left, lo, mid, depth + 1)
insert_value(node.right, mid, hi, depth + 1)
depth = get_depth(root)
output = [[""] * (2**depth - 1) for _ in range(depth)]
insert_value(root, 0, 2**depth - 1)
return output
# @lc code=end