c_cpp 105.从预订和顺序遍历构建二叉树--DraicultyMedium - 2018.9.12

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 105.从预订和顺序遍历构建二叉树--DraicultyMedium - 2018.9.12相关的知识,希望对你有一定的参考价值。

/**
 * 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:
    int findTargetNumIndex(vector<int>& inorder, int num) {
        for (int i = 0; i < inorder.size(); i++) {
            if (num == inorder[i]) {
                return i;
            }
        }
        return -1;
    }
    TreeNode* buildPartTree(vector<int>& inorder, int iL, int iR, vector<int>& preorder, int pL, int pR) {
        if (iL < 0 || iL > iR || iR >= inorder.size() || pL < 0 || pL > pR || pR > preorder.size()) {
            return NULL;
        }
        
        int mid = preorder[pL];
        TreeNode *re = new TreeNode(mid);
        int midIndex = findTargetNumIndex(inorder, mid);
        
        re->left = buildPartTree(inorder, iL, midIndex-1, preorder, pL+1, midIndex-iL+pL);
        re->right = buildPartTree(inorder, midIndex+1, iR, preorder, midIndex-iL+pL+1, pR);
        return re;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildPartTree(inorder, 0 , inorder.size()-1, preorder, 0, preorderv.size()-1);
    }
};

以上是关于c_cpp 105.从预订和顺序遍历构建二叉树--DraicultyMedium - 2018.9.12的主要内容,如果未能解决你的问题,请参考以下文章

java 105.从预订和顺序遍历构建二叉树(#)。java

java 105.从预订和顺序遍历构建二叉树(#)。java

java 105.从预订和顺序遍历构建二叉树(#)。java

java 105.从预订和顺序遍历构建二叉树(#)。java

java 105.从预订和顺序遍历构建二叉树(#)。java

java 105.从预订和顺序遍历构建二叉树(#)。java