103. 二叉树的锯齿形层次遍历
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
在层次遍历的基础上判断层数是偶数还是奇数,偶数不变,奇数数组反转
方法1--队列迭代--BFS
# 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 []
helper = [root]#把根节点存储在队列
res = []
while helper:
tmp1 = []#存储每层节点
tmp2 = [] ###存储左右子树节点
for node in helper:
tmp1.append(node.val)
if node.left:
tmp2.append(node.left)
if node.right:
tmp2.append(node.right)
res.append(tmp1)#这里就是数组里面套数组
helper = tmp2
returnResult=[]
for i, v in enumerate(res):
if i%2==0:
returnResult.append(v)
else:
returnResult.append(v[::-1])#这里每一个里面是一个数组
#result=[[1],[2,3],[4,5,6,7]]
return returnResult
方法2--递归--DFS深层遍历的递归方法
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
res = []
def helper(root, depth):
if not root: return
if len(res) == depth:
res.append([])
if depth % 2 == 0:res[depth].append(root.val)
else: res[depth].insert(0, root.val)#倒序打印,用insert一直往前插入
helper(root.left, depth + 1)
helper(root.right, depth + 1)
helper(root, 0)
return res
网友评论