剑指 Offer 07 重建二叉树

题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

**例如,**给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
在这里插入图片描述
限制:
0 <= 节点个数 <= 5000

方法1:
主要思路:
(1)使用递归;
(2)先找出先序遍历的第一个作为根节点,然后在中序遍历中找出对应的字符所在的位置;
(3)使用中序遍历中找到的位置,计算当前结点左右两边可以有多少个元素,再分别建立左右子树;

/**
 * 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* helper(vector<int>& preorder,vector<int>& inorder,int left_pre,int right_pre,int left_in,int right_in){
        if(left_pre>right_pre){
            return NULL;
        }
        //找出对应元素在中序遍历中的位置
        int index=left_in;
        while(preorder[left_pre]!=inorder[index]){
            ++index;
        }
        TreeNode* root=new TreeNode(preorder[left_pre]);//建立根节点
        //建立左右子树
        root->left=helper(preorder,inorder,left_pre+1,left_pre+index-left_in,left_in,index-1);
        root->right=helper(preorder,inorder,left_pre+index-left_in+1,right_pre,index+1,right_in);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.empty()){
            return NULL;
        }
		//递归建立树
        return helper(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值