topic:
Sword refers to Offer 32-III, print binary tree from top to bottom III
Please implement a function to print the binary tree in zigzag order, that is, the first line is printed from left to right, the second layer is printed from right to left, and the third line is printed from left to right. Others And so on.
For example:
Given a binary tree: [3,9,20,null,null,15,7],
Return the result of its level traversal:
[
[3],
[20,9],
[15,7]
]
prompt:
Total number of nodes <= 1000
Problem solution ideas:
The binary tree is traversed layer by layer by simply using the list, and then each layer is sorted in order and reverse order by parity.
Problem solution python code:
# 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 []
ans, queue = [], collections.deque()
queue.append(root) #初始化queue为root
while queue:
temp = [] #定义层输出列表
for _ in range(len(queue)):
node = queue.popleft() #取出queue最左的元素,并在queue添加左右子树
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
temp.append(node.val) #层输出列表添加node的值
ans.append(temp[::-1] if len(ans)%2!=0 else temp) #按照ans的长度的奇偶情况,判断是否需要逆序
return ans
Author: a-qing-ge
Links: https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/solution/dan-chun-li -yong-lie-biao-dui-er-cha-shu-gjgu/
Source: LeetCode (LeetCode) https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er- cha-shu-iii-lcof/