在层序遍历的基础上添加列表的倒置逻辑,基础还是层序遍历。
import queue
class Solution:
def Print(self , pRoot: TreeNode) -> List[List[int]]:
# write code here
if not pRoot:
return []
q = queue.Queue()
q.put(pRoot)
res = []
reversal_count = 0
while not q.empty():
q_len = q.qsize()
q_res = []
for _ in range(q_len):
temp = q.get()
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
q_res.append(temp.val)
if reversal_count % 2:
q_res = self.list_reversal(q_res)
print(q_res)
res.append(q_res)
reversal_count += 1
return res
def list_reversal(self, res: List[int]) -> list[int]:
temp = []
len_res = len(res)
for i in range(len_res):
temp.append(res[len_res - 1 - i])
return temp