leetcode105 Construct Binary Tree from Preorder and Inorder Traversal
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode105 Construct Binary Tree from Preorder and Inorder Traversal相关的知识,希望对你有一定的参考价值。
1 """ 2 For example, given 3 preorder = [3,9,20,15,7] 4 inorder = [9,3,15,20,7] 5 Return the following binary tree: 6 3 7 / 8 9 20 9 / 10 15 7 11 """ 12 class TreeNode: 13 def __init__(self, x): 14 self.val = x 15 self.left = None 16 self.right = None 17 class Solution(object): 18 def buildTree(self, preorder, inorder): 19 if len(preorder) == 0: 20 return None 21 root_val = preorder[0] 22 root_index = inorder.index(root_val) 23 result = TreeNode(root_val) 24 left_preorder = preorder[1:root_index+1] #比如L=[5,3,6] 25 right_preorder = preorder[root_index+1:] #L[1:3] == [3,6] 26 left_inorder = inorder[:root_index] #实际index是1,2 27 right_inorder = inorder[root_index+1:] 28 result.left = self.buildTree(left_preorder, left_inorder) #递归 29 result.right = self.buildTree(right_preorder, right_inorder) 30 return result 31 """ 32 常见的题,给出前序中序 求二叉树 33 leetcode106为给出中序后序 求二叉树,可相互比较 34 """
以上是关于leetcode105 Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-105-Construct Binary Tree from Preorder and Inorder Traversal
一天一道LeetCode#105. Construct Binary Tree from Preorder and Inorder Traversal
LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal
leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java
leetcode105:Construct Binary Tree from Preorder and Inorder Traversal
LeetCode105 Construct Binary Tree from Preorder and Inorder Traversal