码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal @ Python

时间:2014-05-12 14:24:57      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

原题地址:http://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

题意:根据二叉树的先序遍历和中序遍历恢复二叉树。

解题思路:可以参照 http://www.cnblogs.com/zuoyuan/p/3720138.html 的思路。递归进行解决。

代码:

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

class Solution:
    # @param preorder, a list of integers
    # @param inorder, a list of integers
    # @return a tree node
    def buildTree(self, preorder, inorder):
        if len(preorder) == 0:
            return None
        if len(preorder) == 1:
            return TreeNode(preorder[0])
        root = TreeNode(preorder[0])
        index = inorder.index(root.val)
        root.left = self.buildTree(preorder[1 : index + 1], inorder[0 : index])
        root.right = self.buildTree(preorder[index + 1 : len(preorder)], inorder[index + 1 : len(inorder)])
        return root
        
bubuko.com,布布扣

 

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal @ Python,布布扣,bubuko.com

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal @ Python

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/zuoyuan/p/3720149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!