原題
給出一棵二叉樹(shù),返回其節(jié)點(diǎn)值的鋸齒形層次遍歷(先從左往右,下一層再?gòu)挠彝螅瑢优c層之間交替進(jìn)行)
給出一棵二叉樹(shù) {3,9,20,#,#,15,7}
3
/ \
9 20
/ \
15 7
返回其鋸齒形的層次遍歷為:
[
[3],
[20,9],
[15,7]
]
解題思路
- 相似題[Binary Tree Level Order Traversal]和[Binary Tree Level Order Traversal II]
- 同樣是一個(gè)queue實(shí)現(xiàn)BFS,只是在處理temp結(jié)果的時(shí)候每次改變順序烟央,借助一個(gè)
flag
變量
完整代碼
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import Queue
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
result = []
MyQueue = Queue.Queue()
MyQueue.put(root)
flag = True
while not MyQueue.empty():
size = MyQueue.qsize()
temp = []
for i in range(size):
node = MyQueue.get()
if node.left:
MyQueue.put(node.left)
if node.right:
MyQueue.put(node.right)
if flag:
temp.append(node.val)
else:
temp.insert(0, node.val)
result.append(temp)
flag = not flag
return result