LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal

2592 단어 LeetCode나무.
Given inorder and postorder 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_in(vector<int> &inorder, vector<int> &postorder, int in_start, int post_start, int len) {
        TreeNode* root=NULL;
        if(len==0)
            return NULL;
        if(len==1)
            return new TreeNode(inorder[in_start]);
        int i=0;
        while(inorder[in_start+i]!=postorder[post_start+len-1])
            i++;
        root=new TreeNode(postorder[post_start+len-1]);
        root->left=buildTree_in(inorder,postorder,in_start,post_start,i);
        root->right=buildTree_in(inorder,postorder,in_start+i+1,post_start+i,len-i-1);
        return root;
    }

    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    int len=(int)inorder.size();
    if(len==0)
        return NULL;
    if(len==1)
        return new TreeNode(inorder[0]);
    return buildTree_in(inorder,postorder,0,0,len);
    }

};

update: 
2014 - 12- 22 
사실 위의 사고방식과 기본적으로 같지만 함수 매개 변수가 약간 바뀌었을 뿐이다.
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, int in_start, int in_end, vector<int> &postorder, int post_start, int post_end) {
        TreeNode* root = new TreeNode(postorder[post_end]); 
        if (post_start > post_end) return NULL;
        else if (post_start == post_end) {
            return root;
        }
        int index = 0;
        int left_length = 0;
        for (index = in_start; index <= in_end; ++index) {
            if (inorder[index] == postorder[post_end])
                break;
        }
        left_length = index - in_start;
        root->left = buildTree(inorder, in_start, index - 1, postorder, post_start, post_start + left_length - 1);
        root->right = buildTree(inorder, index+1, in_end, postorder, post_start + left_length, post_end - 1);
        return root;
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return NULL;
        return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }
};

좋은 웹페이지 즐겨찾기