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

题目

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

实现

/**
 * 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 = func(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
        return root;
    }
    TreeNode* func(vector<int>& preorder, int prestart, int preend, vector<int>& inorder, int instart, int inend) {
        if (prestart > preend || instart > inend) return NULL;
        TreeNode* root = new TreeNode(preorder[prestart]);
        int flag = 0;
        for(int i = instart; i <= inend; i++) {
            if (inorder[i] == preorder[prestart]) {
                flag = i;
                break;
            }
        }
        TreeNode* left = func(preorder, prestart + 1, prestart + flag - instart, inorder, instart, flag - 1);
        TreeNode* right = func(preorder,  prestart + flag - instart + 1, preend, inorder, flag + 1, inend);
        root->left = left;
        root->right = right;
        return root;
    }
};
上一篇:vb.net 教程 8-3 数据库操作5


下一篇:1305. All Elements in Two Binary Search Trees