从前序与中序遍历序列构造二叉树—leetcode105

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

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

    3
   / \
  9  20
    /  \
   15   7

 

思路:现在前序遍历中找到第一个数,根据这个数去中序二叉树查找到相应位置,然后根据这个位置就可以得到当前节点的左子树的初始位置和终止位置,并且根据长度直到在前序列表中对应的左子树起始和终止位置,那么递归寻找左子树根节点即可,右子树同理。

/**
 * 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) {
        if(preorder.empty() || inorder.empty())
            return NULL;
        int pre_start = 0; int pre_end = preorder.size()-1;
        int in_start = 0; int in_end = inorder.size()-1;
        return core(preorder, inorder, pre_start, pre_end, in_start, in_end);
    }

    TreeNode* core(vector<int>& preorder, vector<int>& inorder, int pre_start, int pre_end, int in_start, int in_end){
        int rootval = preorder[pre_start];
        TreeNode* root = new TreeNode(rootval);

        if(pre_start == pre_end)
        {
            if((in_start == in_end) && (preorder[pre_start] == inorder[in_end]))
                return root;
            else
                return NULL;
        }

        int in_left_end = -1;
        for(int i=in_start;i<=in_end;++i){
            if(inorder[i]==rootval){
                in_left_end = i;
            }
        }
        if(in_left_end==-1)
            return NULL;
        if(in_left_end-in_start>0)
            root->left = core(preorder, inorder, pre_start+1, pre_start+in_left_end-in_start, in_start, in_left_end-1);
        if(pre_end-(pre_start+in_left_end-in_start)>0)
            root->right = core(preorder, inorder, pre_start+in_left_end-in_start+1, pre_end, in_left_end+1, in_end);
        
        return root;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值