剑指Offer—Python实现(2)

23. 二叉树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

思路:后序遍历的数组中,最后一个元素是根节点。左子树的节点数值都比根节点的数值小,右子树的节点值都比根节点的数值要大。先从根节点开始分析其左子树和右子树。对于左子树,假设有3个节点,且都比根节点要小,则i=3也代表着右节点的位置。利用递归,使得左子树的递归程序中有sequence[:,i],即取数组sequence中的下标是0、1和2的元素。假设同事len(sequence)=7,则对于i而言有3<5成立,sequence[ ]的下标从i=3开始递归。

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        if len(sequence)==0:
            return False
        root = sequence[-1]

        i = 0
        for node in sequence[:-1]:
            if node > root:
                break
            i += 1

        for node in sequence[i:-1]:
            if node < root:
                return False
        left = True
        if i > 1:
            left = self.VerifySquenceOfBST(sequence[:i])

        right = True
        if i < len(sequence) - 2 and left:
            right = self.VerifySquenceOfBST(sequence[i:-1])
        return left and right

24. 二叉树中和为某一数值的路径

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)。

思路:在前序、中序和后序遍历中只有前序遍历是最先访问根节点的,而且题中说在返回的list中数组长度大的数组在前,所以应该采用前序遍历的方法。前序遍历先访问左子树时,在每一个节点的根节点按照从左至右的顺序进行访问。将设定的值expectNumber与所经过的路径中除去最后一个节点的值的和进行相减,然后将结果与遍历的最后一个节点的值进行对比,如果相等的话则说明这条路径是我们所想要的,然后记录下来,返回ret。

class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root, expectNumber):
        # write code here
        ret = []
        def dfs(root,sum_,tmp):
            if root:
                if root.left==None and root.right == None:
                    if root.val == sum_:
                        tmp.append(root.val)
                        ret.append(tmp[:])
                else:
                    tmp.append(root.val)
                    dfs(root.left,sum_-root.val,tmp[:])
                    dfs(root.right,sum_-root.val,tmp[:])
        dfs(root,expectNumber,[])
        return ret

25. 复杂链表的复制

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。

# -*- coding:utf-8 -*-
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
    # 返回 RandomListNode
    def Clone(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """

        if head == None:
            return head
        node_dict = {}
        node_dict[head] = RandomListNode(head.label)
        tmp = head
        while(head):
            random = head.random
            nexthd = head.next
            if random !=None:
                if random not in node_dict:
                    node_dict[random] = RandomListNode(random.label)
                node_dict[head].random = node_dict[random]
            if nexthd !=None:
                if nexthd not in node_dict:
                    node_dict[nexthd] = RandomListNode(nexthd.label)
                node_dict[head].next = node_dict[nexthd]
            head = head.next
        return node_dict[tmp]

26. 二叉搜索树与双向链表

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if pRootOfTree == None:
            return pRootOfTree
        if pRootOfTree.left == None and pRootOfTree.right == None:
            return pRootOfTree
        left = self.Convert(pRootOfTree.left)
        p = left
        if left:
            while(p.right):
                p = p.right
            p.right = pRootOfTree
            pRootOfTree.left = p
        right = self.Convert(pRootOfTree.right)
        if right:
            pRootOfTree.right = right
            right.left = pRootOfTree
        return left if left else pRootOfTree

27. 字符串的排列

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入描述:

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
class Solution:
    def __init__(self):
        self.result=[]
    def Permutation(self, ss):
        # write code here
        s=[]
        to=len(ss)
        for i in range(to):
            s.append(ss[i])
        self.PermutationHelper(s,0,len(ss))
        self.result=list(set(self.result))
        self.result.sort()
        return self.result
    def PermutationHelper(self,ss,fro,to):
        if(to<=0):
            return
        if(fro==to-1):
            self.result.append(''.join(ss))
        else:
            for i in range(fro,to):
                self.swap(ss,i,fro)
                self.PermutationHelper(ss,fro+1,to)
                self.swap(ss,fro,i)
    def swap(self,str,i,j):
        str[i],str[j]=str[j],str[i]

                                                      

猜你喜欢

转载自blog.csdn.net/qq_33335553/article/details/81606756