105. Construct Binary Tree from Preorder and Inorder Traversal

题目描述

Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

代码实现

class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {

        int m = inorder.size();
        int n = preorder.size();
        if(m!=n || m==0)
            return nullptr;
        return buildTreeCore(inorder,0,n-1,preorder,0,n-1);
        
    }
    //涉及到用给定范围的数组元素进行递归,而对于数组,可以用一对
    //下标来表示范围,这一点可以考虑进递归核心函数的参数接口设计上来
    TreeNode *buildTreeCore(vector<int> &inorder,int in_l,int in_r,vector<int> &preorder,int pre_l,int pre_r)
    {    

        if(in_l>in_r)
            return nullptr;
        //这里要注意malloc函数的返回值为void*类型,调用这个函数时
        //我们要强制转换成我们需要的类型
        TreeNode * root = new TreeNode(preorder[pre_l]);
        root->left = nullptr;
        root->right = nullptr;

        int theRoot = in_l;
        //由于题目要求,theRoot的最终的停止位置一定不越界,
        //因为一定有inorder中的一个元素等于root->val
        while(inorder[theRoot]!=root->val)theRoot++;

        root->left = buildTreeCore(inorder,in_l,theRoot-1,preorder,pre_l+1,pre_l+theRoot-in_l);
        root->right = buildTreeCore(inorder,theRoot+1,in_r,preorder,pre_l+theRoot-in_l+1,pre_r);
    
        return root;
    }

   
};

posted on 2021-06-13 06:35  朴素贝叶斯  阅读(18)  评论(0编辑  收藏  举报

导航