前序遍历和中序遍历构造二叉树[lintcode]

这里写图片描述

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        // write your code here
        vector<int> pre_l,pre_r,in_l,in_r;//定义这四个变量来存储左右子树的前序和中序序列
        TreeNode* root=NULL;
         int i=0;
        int index=0;
        if(!preorder.empty()||!inorder.empty())//如果序列中不为空,继续构建
        {
            root=new TreeNode(preorder[0]);


        for(i=0;i<inorder.size();i++)
        {
            if(preorder[0]==inorder[i])
            {
                index=i;//找出分割中序序列的分割点,左边为左子树的,右边为有子树的
              break;
            }

        }
        for(i=0;i<index;i++)//重新找出前面部分前中序列
        {
            pre_l.push_back(preorder[i+1]);
            in_l.push_back(inorder[i]);
        }
        for(i=index+1;i<inorder.size();i++)//找出后面部分的前中序列
        {
            pre_r.push_back(preorder[i]);
            in_r.push_back(inorder[i]);
        }
        //依次构建分割的部分,缩小区间,直至构建完
        root->left=buildTree(pre_l,in_l);
        root->right=buildTree(pre_r,in_r);
        }
        return root;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值