LeetCode: Construct Binary Tree from Preorder and Inorder Traversal

思路:记录好中序、后序在数组中的其实位置和当前元素个数,计算好左右子树根节点在数组中的位置和左右子树元素个数,只要左右子树的个数都为0,就会递归终止,返回叶子节点的指针,重复这一过程就是构造出了树结构。

code:

class Solution {
public:
    TreeNode * buildTreePreInOrder(vector<int>::iterator preIt,vector<int>::iterator inIt, int num){
        TreeNode * root = new TreeNode(*preIt);
        vector<int>::iterator it = inIt;
        while(*it != *preIt)
            it++;
        int numLeft = it - inIt, numRight = num - numLeft - 1;
        if(numLeft > 0)
            root->left = buildTreePreInOrder(preIt+1,inIt,numLeft);
        if(numRight >0) 
            root->right = buildTreePreInOrder(preIt+numLeft+1,inIt+numLeft+1,numRight);
        return root;
    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        TreeNode * root;
        if(!preorder.empty())
            root = buildTreePreInOrder(preorder.begin(),inorder.begin(),inorder.size());
        else
            return NULL;
        return root;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值