Sword refers to Offer ------- Rebuild the binary tree

Insert picture description here

Topic link!

Idea: For
this question, we only need to know the traversal characteristics of the binary tree. The first number of the pre-order array is the value of the first root node we want to establish, then we need to traverse the in-order array to get For the division of left and right subtrees, we know that the middle order is LDR, so the left subtree must be on the left of the root node x, and the recursion is enough.


 * 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 {
	//当然,这道题也可以换成  判断能否构成二叉树
    TreeNode* dfs(vector<int>& t1,int left1,int right1,vector<int>& t2,int left2,int right2){
        if(left1>right1) return NULL;
        int rt = t1[left1]; 
        TreeNode* root = new TreeNode(rt);
        if(right1==left1) return root;

        int i=0;
        for( i=left2;i<=right2;++i){
        root->left = dfs(t1,left1+1,left1+(i-left2),t2,left2,i-1);
        root->right = dfs(t1,left1+(i-left2)+1,right1,t2,i+1,right2);
        return root;
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.size()==0 || inorder.size()==0) return NULL;
        return dfs(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115065745