Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:读写加密锁软件 编辑:程序博客网 时间:2024/04/30 23:17

题目大意:给定二叉树前序遍历和后序遍历的两个序列,要求通过这两个序列还原出二叉树

解题思路:递归求每个子树的根节点


/** * Definition for binary tree * 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) {        if(preorder.size() != inorder.size()) {            return NULL;        }        int startIndex = 0;        return buildTreeAssist(preorder, startIndex, inorder, 0, inorder.size() - 1);    }private:    TreeNode *buildTreeAssist(vector<int> &preorder, int &pstartIndex, vector<int> &inorder, int istartIndex, int iendIndex) {        if(pstartIndex >= preorder.size()) {            return NULL;        }        if(istartIndex > iendIndex || iendIndex >= inorder.size()) {            return NULL;        }        int index = istartIndex;        while(index <= iendIndex) {            if(inorder[index] == preorder[pstartIndex]) {                break;            }            index++;        }        if(index > iendIndex) {            return NULL;        }        TreeNode *root = new TreeNode(preorder[pstartIndex]);        if(istartIndex <= index - 1) {            pstartIndex++;            root->left = buildTreeAssist(preorder, pstartIndex, inorder, istartIndex, index - 1);        }        if(index + 1 <= iendIndex) {            pstartIndex++;            root->right = buildTreeAssist(preorder, pstartIndex, inorder, index + 1, iendIndex);        }        return root;    }};


0 0
原创粉丝点击