LetCode 105. 从前序与中序遍历序列构造二叉树

/**
 * 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& preorder, vector& inorder) {
        return buildTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
    }
    
    TreeNode* buildTree(vector& preorder, vector& inorder, int pre_left, int pre_right, int in_left, int in_right){
        if (pre_left > pre_right || in_left > in_right)
            return NULL;
        int rootVal = preorder[pre_left];// 前序遍历中的第一个节点为当前树的根节点
        TreeNode* root = new TreeNode(rootVal);
        // 在中序序列中找到当前根节点
        int index = distance(inorder.begin(), find(inorder.begin(), inorder.end(), rootVal));
        // 算出左子树和右子树的节点个数
        int left_num = index - in_left;
        int right_num = in_right - index;
        // 最后递归构建左右子树
        root->left = buildTree(preorder, inorder, pre_left + 1, pre_left + left_num, in_left, index - 1);
        root->right = buildTree(preorder, inorder, pre_left + left_num + 1, pre_right, index + 1, in_right);
        return root;
    }    
};

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

 

你可能感兴趣的:(LeetCode)