剑指 Offer 32 - II. 从上到下打印二叉树 II

剑指 Offer 32 - II. 从上到下打印二叉树 II
剑指 Offer 32 - II. 从上到下打印二叉树 II_第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 not root:
            return list(list())
        #其次解决遍历情况
        queue = collections.deque()
        queue.append(root)
        res = []
        while len(queue):
            tmpRes = []
            for _ in range(len(queue)):
                tmpNode = queue.popleft()
                tmpRes.append(tmpNode.val)
                if tmpNode.left is not None: queue.append(tmpNode.left)
                if tmpNode.right is not None: queue.append(tmpNode.right)
            res.append(tmpRes)
        return res

剑指 Offer 32 - III. 从上到下打印二叉树 III
剑指 Offer 32 - II. 从上到下打印二叉树 II_第2张图片

# 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 not root:
            return list(list())

        deque = collections.deque()
        res = []
        deque.append(root)

        leftRight = True
        while len(deque):
            tmpRes = []
            for _ in range(len(deque)):
                tmpNode = deque.popleft()
                tmpRes.append(tmpNode.val)
                if tmpNode.left is not None: deque.append(tmpNode.left)
                if tmpNode.right is not None: deque.append(tmpNode.right)
            if leftRight == False:
                tmpRes1 = []
                for i in range(len(tmpRes)-1, -1, -1):
                    tmpRes1.append(tmpRes[i])
                tmpRes = tmpRes1
            res.append(tmpRes)
            leftRight = False if leftRight else True

        return res

剑指 Offer 33. 二叉搜索树的后序遍历序列
剑指 Offer 32 - II. 从上到下打印二叉树 II_第3张图片

class Solution:
    def verifyPostorder(self, postorder: List[int]) -> bool:
        #二叉搜索树(根节点在最后)
        if len(postorder) < 1:
            return True
        else:
            rootData = postorder[-1]
            smallId, smallFlag = -1, True
            leftRoot = []
            rightRoot = []
            for i in range(len(postorder)-1):
                if smallFlag:
                    if postorder[i] < rootData:
                        smallId = i
                        leftRoot.append(postorder[i])
                    if postorder[i] > rootData:
                        smallFlag = False
                        rightRoot.append(postorder[i])
                else:
                    if postorder[i] < rootData:
                        return False
                    else:
                        rightRoot.append(postorder[i])

            return self.verifyPostorder(leftRoot) and self.verifyPostorder(rightRoot)

你可能感兴趣的:(力扣)