题目:
二叉树的锯齿形层次遍历:给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
思路:
使用层序遍历的思路,但是没有用到栈。
程序:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] result = [] current_level = [root] index = 0 while current_level: auxiliary = [] next_level = [] for node in current_level: auxiliary.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) if index % 2 == 1: result.append(auxiliary[::-1]) if index % 2 == 0: result.append(auxiliary) index += 1 current_level = next_level return result