LeetCode105—Construct Binary Tree from Preorder and Inorder Traversal

LeetCode105—Construct Binary Tree from Preorder and Inorder Traversal

原题

Given preorder and inorder traversal of a tree, construct the binary tree.

给出树的先序和中序遍历,构建二叉树。

分析

这题以前数据结构考试题中用,先序遍历可以可以找出树的根,中序遍历可以找出树的左右子树,如此递归下去,可以构建树。
根据此:
1. 在先序遍历中找到根
2. 在中序遍历中找到根对应的位置,即可把中序分为左右两子树
3. 计算在先序遍历中,分别计算左右子树中根的位置
4. 递归左右子树

关于第2点,我们需要提前建立一个map来找出根和中序遍历中索引的对应关系。

代码

class Solution {
private:
    TreeNode* helper(vector<int>&preorder, vector<int>&inorder, map<int, int>&index, int pstart, int pend, int istart, int iend)
    {
        if (istart > iend)
            return NULL;
        int rootval = preorder[pstart];//根
        int rootindex = index[rootval];//根在中序中的索引
        TreeNode* root = new TreeNode(rootval);
        root->left = helper(preorder, inorder, index, pstart + 1, pstart + rootindex - istart, istart, rootindex - 1);//递归左子树
        root->right = helper(preorder, inorder, index, pstart + rootindex - istart + 1, pend, rootindex + 1, iend);//递归右子树
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        map<int, int>index;
        for (int i = 0; i < inorder.size(); i++)
        {
            index[inorder[i]] = i;//建立值与索引的关系
        }
        return helper(preorder, inorder, index,0, preorder.size() - 1, 0, inorder.size() - 1);
    }
};//一定要使用引用否则会超时

这里传参数时一定要使用引用否则会超时。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值