Leetcode:.. 105 previous order and sequence preorder binary tree structure and sequence from 106 & postorder binary sequence structure

Leetcode: 105. previous order and configured binary sequence preorder & 106. The sequence from the sequence postorder binary tree structure

Leetcode: 105. previous order and configured binary sequence preorder & 106. The sequence from the sequence postorder binary tree structure

This question is a classic template topic friends ~

After pre-order traversal sequence results in the sequence of template please achievements Jump to: order before and after the establishment of tree or directly over calendar

Direct dictation! ! !

105. previous order and a binary tree configuration sequence preorder

/**
 * 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:
    vector<int> preOrder,inOrder;
    TreeNode* built(int root,int start,int end,TreeNode* tree){
        if(start>end) return NULL;
        if(tree==NULL) tree=new TreeNode(preOrder[root]);
        int index=start;
        while(inOrder[index]!=preOrder[root]) index++;
        tree->left=built(root+1,start,index-1,tree->left);
        tree->right=built(root+index-start+1,index+1,end,tree->right);
        return tree;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        preOrder=preorder,inOrder=inorder;
        TreeNode* tree=NULL;
        tree=built(0,0,preOrder.size()-1,tree);
        return tree;
    }
};

106. The sequence from the sequence postorder binary tree structure

/**
 * 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:
    vector<int> inOrder,postOrder;
    TreeNode* build(int root,int start,int end,TreeNode* tree){
        if(start>end) return NULL;
        if(tree==NULL) tree=new TreeNode(postOrder[root]);
        int index=start;
        while(postOrder[root]!=inOrder[index]) index++;
        tree->left=build(root-end+index-1,start,index-1,tree->left);
        tree->right=build(root-1,index+1,end,tree->right);
        return tree;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        inOrder=inorder,postOrder=postorder;
        TreeNode* tree=NULL;
        tree=build(inOrder.size()-1,0,inOrder.size()-1,tree);
        return tree;
    }
};

Guess you like

Origin www.cnblogs.com/cell-coder/p/12354859.html