zoukankan      html  css  js  c++  java
  • Construct Binary Tree from Preorder and Inorder Traversal

    题目要求给出前序和中序二叉树遍历结果,重建二叉树。树的节点值不存在冗余。

    解法是给出目前处理的前序和中序的起始和结束的index。前序的第一个值为根节点的值,根据这个值在中序中查找index,从而在中序中划分左子树和右子树的遍历,递归求解,直至只有一个节点。注意为了进行中序遍历的高效查找,预先把值存入hashmap之中,python的实现为dict.

    class Solution(object):
        def buildTree(self, preorder, inorder):
            """
            :type preorder: List[int]
            :type inorder: List[int]
            :rtype: TreeNode
            """
            
            if not preorder:
               return None
            map ={}
            length = len(preorder)
            for i in xrange(length):
               map[inorder[i]] = i
            return self.helper(preorder,0,length-1,0,length-1,map)
            
        def helper(self,preorder,Pstart,Pend,Istart,Iend,map):
            if Pstart > Pend:
               return None
            node = TreeNode(preorder[Pstart]) 
            if Pstart == Pend:
               return node
            i = map[preorder[Pstart]]
            
            node.left = self.helper(preorder,Pstart+1,i-Istart+Pstart,Istart,i-1,map)
            node.right = self.helper(preorder,i-Istart+Pstart+1,Pend,i+1,Iend,map)
            return node
    

     时间复杂度为O(n),每个结点都需要遍历一遍,递归函数栈的大小为O(logn)。因为建立了dict,最终空间复杂度为O(n),

  • 相关阅读:
    使用Junit等工具进行单元测试
    软件工程学习、问题
    贪吃蛇
    使用Junit工具进行单元测试
    两人组
    软件工程的理解
    使用工具进行单元测试
    对软件工程的理解
    单元测试
    我对软件工程的理解
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5405686.html
Copyright © 2011-2022 走看看