二叉树的锯齿形层次遍历
作者:
而立之年的技术控 | 来源:发表于
2019-12-24 18:46 被阅读0次
说一点:遇到这种层次遍历(不管他什么奇葩要求),思路只有一条:那就是使用【两个辅助栈】轻松解决

WechatIMG23.jpeg
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return None
stack1 = [root]
stack2 = []
ret = []
while stack1 or stack2:
if stack1:
tmpList = []
while stack1:
tmp = stack1[0]
tmpList.append(tmp.val)
if tmp.left:
stack2.append(tmp.left)
if tmp.right:
stack2.append(tmp.right)
del stack1[0]
ret.append(tmpList)
if stack2:
tmpList = []
while stack2:
tmp = stack2.pop()
tmpList.append(tmp.val)
if tmp.right:
stack1.insert(0,tmp.right)
if tmp.left:
stack1.insert(0,tmp.left)
ret.append(tmpList)
return ret
本文标题:二叉树的锯齿形层次遍历
本文链接:https://www.haomeiwen.com/subject/wovfoctx.html
网友评论