[leetcode]python3 算法攻略-二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

方案一:先进先出

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None:
            return []
        stack = [root]
        yy = []
        while stack:
            y = []
            l = len(stack)
            for i in range(l):     
                cur = stack.pop(0)
                y.append(cur.val)
                if cur.left:
                    stack.append(cur.left)
                if cur.right:
                    stack.append(cur.right)
            yy.append(y)
        return yy

方案二:

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root: return []

        ret = []
        curList = [root]
        while curList:
            ret.append([i.val for i in curList])

            nextList = []
            for i in curList:
                if i.left: nextList.append(i.left)
                if i.right: nextList.append(i.right)
            curList = nextList
        return ret

猜你喜欢

转载自blog.csdn.net/zhenghaitian/article/details/81049952