本文共 770 字,大约阅读时间需要 2 分钟。
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.For example, given
preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
根据前序遍历和中序遍历生成二叉树。
用递归方法很容易完成,先利用前序遍历找到根节点,然后再根据中序遍历分根节点的左子树和右子树。
需要注意的是和后序+中序有所不同,前序+中序要先写root.left,而前者要先写root.right。
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if inorder: prenode=preorder.pop(0) index = inorder.index(prenode) root=TreeNode(inorder[index]) root.left=self.buildTree(preorder, inorder[:index]) root.right=self.buildTree(preorder, inorder[index+1:]) return root
转载地址:http://odrbb.baihongyu.com/