欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【C++】【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal

程序员文章站 2022-03-03 10:13:05
...

题目

Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

思路

前序排列,根结点在最前面;中序排列,根结点前面是左子树的结点,后面是右子数的结点。以此将左右子树分开,又可以按照前序排列继续分割。

代码

/**
 * 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<int>& preorder, vector<int>& inorder) {
        TreeNode* root;
        if (preorder.size() == 0) {
            return NULL;
        }
        root = helper(root, preorder, 0, preorder.size() - 1, inorder, 0, preorder.size() - 1);

        return root;
    }

    TreeNode* helper(TreeNode* root, vector<int>& preorder, int start1, int end1, vector<int>& inorder, int start2, int end2) {
        if (end1 < start1) {
            return root;
        } else {
            root = new TreeNode(preorder[start1]);
            int i = 0;
            for (; i < end2-start2; i++) {
                if (inorder[i+start2] == preorder[start1]) {
                    break;
                }
            }

            root->left = (i < 1) ? NULL : helper(root->left, preorder, start1 + 1, i+start1, inorder, start2, start2 + i - 1);
            root->right = (i + start1 + 1 > end1) ? NULL : helper(root->right, preorder, i+start1 + 1, end1, inorder, i+start2 + 1, end2);
            return root;
        }

    }
};
相关标签: leetcode