class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder or not postorder: return None tree_root = TreeNode(postorder.pop()) tree_root_index = inorder.index(tree_root.val) tree_root.right = self.buildTree(inorder[tree_root_index + 1:], postorder) tree_root.left = self.buildTree(inorder[:tree_root_index], postorder) return tree_root
Leetcode练习(Python):数组类:第106题:根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。
题目:
根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。
思路:
与第105题类似,区别是前序遍历一开始找的是左子树的结点,后续遍历一开始找的是右子树的结点,因为从后面开始找数字。
程序:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder or not postorder: return None tree_root = TreeNode(postorder.pop()) tree_root_index = inorder.index(tree_root.val) tree_root.right = self.buildTree(inorder[tree_root_index + 1:], postorder) tree_root.left = self.buildTree(inorder[:tree_root_index], postorder) return tree_root
class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder or not postorder: return None tree_root = TreeNode(postorder.pop()) tree_root_index = inorder.index(tree_root.val) tree_root.right = self.buildTree(inorder[tree_root_index + 1:], postorder) tree_root.left = self.buildTree(inorder[:tree_root_index], postorder) return tree_root