중차 반복 + 후차 반복/전차 반복 구축 두 갈래 트리

5513 단어
제목 1: 중차 역행 + 후차 역행 Given inorder andpostorder traversal of a tree,construct the binary tree.Note: You may assume that duplicates do not exist in the tree.
/**
 * 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> &inorder, vector<int> &postorder) {
        return dfs(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
    TreeNode *dfs(vector<int> &inorder,int in_left,int in_right,vector<int> &postorder,int post_left,int post_right)
    {
        if(in_left>in_right)
            return NULL;

        int mid=in_left;
        for(;mid<=in_right;mid++)
        {
            if(inorder[mid]==postorder[post_right])
                break;
        }
        TreeNode *root=new TreeNode(inorder[mid]);
        int in_left_length=mid-in_left;
        // , , [in_left,mid-1]、[mid+1,in_right]
        // , , [post_left,post_left+in_left_length-1]、[post_left+in_left_length,post_right-1]
        root->left=dfs(inorder,in_left,mid-1,postorder,post_left,post_left+in_left_length-1);//
        root->right=dfs(inorder,mid+1,in_right,postorder,post_left+in_left_length,post_right-1);
        return root;
    }
};

제목2: 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 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) {
        return dfs(inorder,0,inorder.size()-1,preorder,0,preorder.size()-1);
    }
    TreeNode *dfs(vector<int> &inorder,int in_left,int in_right,vector<int> &preorder,int pre_left,int pre_right)
    {
        if(in_left>in_right)
            return NULL;

        int mid=in_left;
        for(;mid<=in_right;mid++)
        {
            if(inorder[mid]==preorder[pre_left])
                break;
        }
        TreeNode *root=new TreeNode(inorder[mid]);
        int in_left_length=mid-in_left;
        // , , [in_left,mid-1]、[mid+1,in_right]
        // , , [pre_left+1,pre_left+in_left_length]、[pre_left+in_left_length+1,pre_right]
        root->left=dfs(inorder,in_left,mid-1,preorder,pre_left+1,pre_left+in_left_length);//
        root->right=dfs(inorder,mid+1,in_right,preorder,pre_left+in_left_length+1,pre_right);
        return root;
    }
};

좋은 웹페이지 즐겨찾기