103.二叉树的锯齿形层次遍历
题目
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
方法
方法1:宽度优先遍历 & dict
Using dic to store the values of each level’s nodes in corresponding lists. When return the result, reverse every other level.
1 | # Definition for a binary tree node. |
方法2:宽度优先遍历 & list
Simple straightforward solution using flag to decide whether from left to right or from right to left
1 | # Definition for a binary tree node. |
1 | class Solution(object): |
1 | # Definition for a binary tree node. |