本文主要是介绍105. Construct Binary Tree from Preorder and Ignorer Traversal【M】【35】【再来一遍】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution(object):def buildTree(self, preorder, inorder):if inorder:val = preorder.pop(0)pos = inorder.index(val)root = TreeNode(val)root.left = self.buildTree(preorder,inorder[:pos])root.right = self.buildTree(preorder,inorder[pos+1:])return root'''if not p:return None#print p,i,i.index(p[0])if len(p) == 1:return TreeNode(p[0])val = p[0]pos = i.index(val)root = TreeNode(val)root.left = self.buildTree(p[1:pos+1],i[0:pos])root.right = self.buildTree(p[pos+1:],i[pos+1:])return root'''""":type preorder: List[int]:type inorder: List[int]:rtype: TreeNode"""
这篇关于105. Construct Binary Tree from Preorder and Ignorer Traversal【M】【35】【再来一遍】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!