vlambda博客
学习文章列表

中序后续/中序前序构造二叉树

#按题目例子把图画出来,有特殊到一般即可,就能找到过滤,后序遍历,根节点在最后,前序遍历根节点在最前面。# 树节点三要素,值,左节点,右节点。无非是把这些定义出来。#按题目例子把图画出来,有特殊到一般即可class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
class Solution: def buildTree(self, inorder, postorder) -> TreeNode: if not inorder: return None root = TreeNode(postorder[-1]) i = inorder.index(root.val) root.left = self.buildTree(inorder[:i], postorder[:i]) root.right = self.buildTree(inorder[i+1:], postorder[i:-1]) return root



#按题目例子把图画出来,有特殊到一般即可,就能找到过滤,后序遍历,根节点在最后,前序遍历根节点在最前面。# 树节点三要素,值,左节点,右节点。无非是把这些定义出来。
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: # 实际上inorder 和 postorder一定是同时为空的,因此你无论判断哪个都行 if not preorder: return None root = TreeNode(preorder[0]) i = inorder.index(root.val) root.left = self.buildTree(preorder[1:i + 1], inorder[:i]) root.right = self.buildTree(preorder[i + 1:], inorder[i+1:])
return root