# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
stack1 = []
stack2 = []
stack1.append(root)
ans = []
while (not (stack1 == [] and stack2 == [])):
tempAns = []
while (stack1 != []):
temp = stack1.pop()
tempAns.append(temp.val)
if temp.left != None:
stack2.append(temp.left)
if temp.right != None:
stack2.append(temp.right)
ans.append(tempAns)
tempAns = []
if stack1 == [] and stack2 == []:
break
stack2.reverse()
while (stack2 != []):
temp = stack2.pop()
tempAns.append(temp.val)
if temp.left != None:
stack1.append(temp.left)
if temp.right != None:
stack1.append(temp.right)
ans.append(tempAns)
stack1.reverse()
return ans
层次遍历 栈