天天看点

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);
    }
};