【剑指Offer系列07】重建二叉树

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

3
/
9 20
/
15 7

限制:
0 <= 节点个数 <= 5000

代码

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 思想:
# 1.得到前序根结点
# 2.搜索根节点在中序索引,划分左右子树
# 3.分别递归遍历左右子树
# 复杂度:O(N),N是节点数量,前提是建立哈希表再搜索根节点在中序索引会是O(1),以空间换时间
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        self.hashmap,self.po={},preorder
        # 建立中序遍历哈希表
        for i in range(len(inorder)):
            self.hashmap[inorder[i]]=i
        return self.recur(0,0,len(inorder)-1) # 开启递归,返回各子树根节点
    
    def recur(self, pre_root, in_left, in_right)->TreeNode:
        # 子树递归函数
        # 输入:前序根节点索引,中序子树左边界,中序子树右边界
        # 输出:子树根节点
        if in_left>in_right: return # 递归终止条件:左边界>右边界
        root=TreeNode(self.po[pre_root]) # 建立根节点
        i=self.hashmap[root.val] # 返回根节点在中序遍历的索引
        root.left=self.recur(pre_root+1,in_left,i-1) # 这里的三个索引一定要理清
        root.right=self.recur(pre_root+i-in_left+1,i+1,in_right)
        return root

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    unordered_map<int,int> hashmap;
    vector<int> po;
    
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        po=preorder;
        for (int i=0;i<inorder.size();i++) {
            hashmap[inorder[i]]=i;
        }
        TreeNode* root=recur(0,0,inorder.size()-1);
        return root;
    }
    
    TreeNode* recur(int pre_root,int in_left,int in_right) {
        if (in_left>in_right) return NULL;
        TreeNode* root=new TreeNode(po[pre_root]);
        int i=hashmap[root->val];
        root->left=recur(pre_root+1,in_left,i-1);
        root->right=recur(pre_root+i-in_left+1,i+1,in_right);
        return root;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章