天天看點

LeetCode - 105. Construct Binary Tree from Preorder and Inorder Traversal

題目
  1. Construct Binary Tree from Preorder and Inorder Traversal
題目連結

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

參考部落格

https://www.cnblogs.com/grandyang/p/4296500.html

解題思路

這類題之前做過總結,即,采用四個參數,指定先序、中序中左(右)子樹的左邊界和右邊界。在确定邊界參數時盡量使用左(右)子樹的長度計算。最後參考部落格添加了

if (start1 > end1 || start2 > end2) return nullptr;

遞歸終結條件(其實在總結中有提)。

解題源碼
/**
 * 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* build(vector<int>& preorder, vector<int>& inorder, int start1, int end1, int start2, int end2){
        if (start1 > end1 || start2 > end2) return nullptr;
        TreeNode* root = new TreeNode(preorder[start1]);
        root->left = nullptr;
        root->right = nullptr;
        int index = start2;
        while (index <= end2 && preorder[start1] != inorder[index]) index++;
        root->left = build(preorder, inorder, start1 + 1, start1 + index - start2, start2, index - 1);
        root->right = build(preorder, inorder, start1 + index - start2 + 1, end1, index + 1, end2);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int len = preorder.size();
        return build(preorder, inorder, 0, len - 1, 0, len - 1);
    }
};