首页 > 编程语言 > 详细

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

时间:2014-05-12 14:22:23      阅读:389      评论:0      收藏:0      [点我收藏+]

原题地址: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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!