Leetcode刷题记录——102. 二叉树的层序遍历

Leetcode刷题记录——102. 二叉树的层序遍历_第1张图片
简单方法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def __init__(self):
        self.res = []
        self.length = 0
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        self.func(root,1)
        return self.res
    def func(self,root,depth):
        if root == None:
            return None
        if depth > self.length:
            self.res.append([root.val])
            self.length += 1
        else:
            self.res[depth-1].append(root.val)
        self.func(root.left,depth+1)
        self.func(root.right,depth+1)

复杂方法
注意 如果每层按先左后右的顺序入栈
需要在下一层之前反转一次

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if root == None:
            return []
        stack = [root]
        cnt = 1
        res = []
        while stack != []:
            nextcnt = 0
            tempres = []
            length = len(stack)
            tempstack = []
            for i in range(cnt):
                temproot = stack.pop()
                if temproot == None:
                    continue
                else:
                    tempres.append(temproot.val)
                    if temproot.left != None:
                        tempstack.append(temproot.left)
                        nextcnt += 1
                    if temproot.right != None:
                        tempstack.append(temproot.right)
                        nextcnt += 1
            res.append(tempres)
            stack = tempstack[::-1]
            cnt = nextcnt
        return res

你可能感兴趣的:(leetcode,python编程技巧)