您的位置:首页 > 其它

LeetCode之Construct Binary Tree from Preorder and Inorder Traversal

2018-01-07 11:54 316 查看
Given preorder and inorder traversal of a tree, construct the binary tree.

题目意思:给定前序和中序遍历,构建一个二叉树

思路:假设前序遍历的起始位置startPre,结束位置endPre,中序遍历:startIn,endIn

由前序遍历和中序遍历,可以确定哪边是左子树,哪边是右子树。在前序遍历中对应中序遍历,首先确定树根,即前序遍历第一个,对应中序遍历中的第i个数,然后可以根据“根”在中序遍历的位置:startPre+i-startIn划分左右子树范围;构建左子树,对应前序遍历的(0,startPre+i-startIn),同样确定它是不是在中序遍历的前半段,不是,就构建右子树,则是(startPre+i-startIn+1,end);



/**

 * 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 {

public:

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {

        TreeNode *root=rebuild(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);

        return root;

    }

    TreeNode* rebuild(vector<int>& Pre,int startPre,int endPre,vector<int>& In,int startIn,int endIn){

        if(startPre>endPre||startIn>endIn)

            return NULL;

        TreeNode *root=new TreeNode(Pre[startPre]);

        for(int i=startIn;i<=endIn;i++){

            if(In[i]==Pre[startPre]){

                root->left=rebuild(Pre,startPre+1,startPre+i-startIn,In,startIn,i-1);

                root->right=rebuild(Pre,i-startIn+startPre+1,endPre,In,i+1,endIn);

            }

        }

        return root;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: