剑指Offer-Python(21-25)

21、栈的压入和弹出序列

新建一个栈,将数组A压入栈中,当栈顶元素等于数组B时,就将其出栈,当循环结束时,判断栈是否为空,若为空则返回true.

class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if len(pushV) != len(popV):
            return False
        stack = []
        for i in pushV:
            stack.append(i)
            # print(stack[-1], popV[0])
            while len(stack) != 0 and stack[-1] == popV[0]:
                # t = stack.pop()
                stack.pop()
                popV.pop(0)
                # print(t)
        return len(stack) == 0


s = Solution()
push1 = [1, 2, 3, 4, 5]
pop1 = [4, 5, 3, 2, 1]
pop2 = [4, 5, 3, 1, 3]
print(s.IsPopOrder(push1, pop1))  # true
print(s.IsPopOrder(push1, pop2))  # False

22、从上往下打印二叉树:

从根节点开始依次把每一层的树节点值放入v中,同时把该树节点的子节点放入p中。按前面的操作,直到p为空。(层序遍历二叉树)

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        p = []
        v = []
        if root:
            p.append(root)
        while p:
            v.append(p[0].val)
            if p[0].left:
                p.append(p[0].left)
            if p[0].right:
                p.append(p[0].right)
            p.pop(0)
        return v


s = Solution()
tree1 = TreeNode(1)
t1 = TreeNode(6)
t2 = TreeNode(8)
t3 = TreeNode(4)
t4 = TreeNode(5)
tree1.left = t1
tree1.right = t2
t1.left = t3
t3.right = t4

t5 = TreeNode(14)
t6 = TreeNode(12)
t7 = TreeNode(16)
t2.right = t5
t5.left = t6
t5.right = t7

print(s.PrintFromTopToBottom(tree1))

 

23、二叉搜索树的后序遍历序列

后序遍历 的序列中,最后一个数字是树的根节点 ,数组中前面的数字可以分为两部分:第一部分是左子树节点 的值,都比根节点的值小;第二部分 是右子树 节点的值,都比 根 节点 的值大,后面用递归分别判断前后两部分 是否 符合以上原则

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        if len(sequence) == 0:
            return False
        l = len(sequence)
        root = sequence[l - 1]
        for i in range(l):
            if sequence[i] > root:
                break
        for j in range(i, l):
            if sequence[j] < root:
                return False
        left = True
        right = True
        if i > 0:
            left = self.VerifySquenceOfBST(sequence[0:i])
        if i < l - 1:
            right = self.VerifySquenceOfBST(sequence[i:l - 1])
        return left and right


s = Solution()
sp = [5, 4, 6, 12, 16, 14, 8, 7]
sp1 = [7, 6, 8, 4, 14, 5, 12, 16]
print(s.VerifySquenceOfBST(sp))
print(s.VerifySquenceOfBST(sp1))
posted @ 2019-12-11 14:25  +D  阅读(296)  评论(0编辑  收藏  举报