Skip to content

Latest commit

 

History

History
49 lines (45 loc) · 1.33 KB

102.md

File metadata and controls

49 lines (45 loc) · 1.33 KB
# 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
            

层次遍历 栈