算法:Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:软件测试职位描述 编辑:程序博客网 时间:2024/06/05 06:10

Given preorder and inorder traversal of a tree, construct the binary 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 {private:    // 为了避免数组的复杂操作,这里直接用左右界和数组的引用来代表一段前序遍历和中序遍历    // 即preorder[lp, rp]代表了当前子树的前序遍历,inorder[li, ri]代表了当前子树的中序遍历    TreeNode* work(vector<int>& preorder, vector<int>& inorder, int lp, int rp, int li, int ri) {        // 判断长度为0的情况        if (lp > rp) return NULL;        // 设置根节点        TreeNode *root = new TreeNode(preorder[lp]);        // 找到根节点在inorder中的位置        for (int k = li; k <= ri; k++) {            if (preorder[lp] == inorder[k]) {                // 分治处理两棵子树                root -> left = work(preorder, inorder, lp + 1, lp + (k - li), li, k - 1);                root -> right = work(preorder, inorder, lp + (k - li) + 1, rp, k + 1, ri);            }        }        // 返回这棵子树        return root;    }    public:    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {        if(preorder.size()==0 || inorder.size()==0)            return NULL;                return work(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);    }};


0 0
原创粉丝点击