<검지 Offer(2판)> 면접문제 32 - III. 위에서 아래로 두 갈래 나무 인쇄 III
1115 단어 LeetCode 포인트
, , , , 。
:
: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
:
[
[3],
[20,9],
[15,7]
]
:
<= 1000
,
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
q = []
temp = []
q.append(root)
level = 1
index = 0
result = [[root.val]]
while q[index:]:
if q[index].left:
temp.append(q[index].left)
if q[index].right:
temp.append(q[index].right)
if index == len(q)-1:
result.append([i.val for i in temp])
for i in temp:
q.append(i)
temp = []
level += 1
index += 1
for i in range(1, len(result), 2):
result[i] = result[i][::-1]
return result[:-1]