方法1
# -*- coding:utf-8 -*-
"""
Author: leadingme
Mail:[email protected]
MyWebsite:leadingme.top
"""
# 二叉樹的層次遍歷
"""
算法要求:
給定一顆二叉樹,返回其按層次遍歷的節點值(逐層地,從左到右訪問所有節點)
示例:
輸入: 3
/ \
9 20
/ \
15 7
輸出: [[3],[9,20],[15,7]]
解題思路:
以層爲單位操作,數的層數越深,節點就越多,且對順序有要求,所以可以對層進行迭代
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root: TreeNode) ->list:
rList = [] # 用來保存最終返回的節點值數組
subList = [] # 暫時存儲上一層節點值
if root is None:
return rList
else:
cNodeList = [root] # 上一層節點數組
nNodeList = [] # 下一層節點數組
while True:
if cNodeList: #
node = cNodeList.pop(0) # 彈出上一層節點數組的第一個值
subList.append(node.val)
if node.left and node.right: # 上一層的節點擁有左右節點,則把它的左右節點加入到下一層節點數組中
nNodeList.append(node.left)
nNodeList.append(node.right)
elif node.left: # 上一層的節點只擁有左節點,則把它的左節點加入到下一層節點數組中
nNodeList.append(node.left)
elif node.right: # 上一層的節點只擁有右節點,則把它的右節點加入到下一層節點數組中
nNodeList.append(node.right)
else:
pass
else:
# 這裏的subList[:]中用到的[:]類似於深度拷貝,改變原數組值,不會影響它,有關知識可以看以下鏈接
rList.append(subList[:]) # 將sublist的值(上一層節點的值)賦值給rList
subList = [] # 置空
if not nNodeList:
break
else:
cNodeList = nNodeList[:]
nNodeList = []
return rList
方法2
from collections import deque
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = []
queue = deque()
queue.append(root)
while queue:
cur = queue.popleft()
if cur:
res.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
else:
res.append(None)
while res and res[-1]==None:
res.pop()
return res
list[:]深度拷貝用法:
https://www.jianshu.com/p/88f4b426d18d