LeetCode: Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

找到根节点在中序遍历中的index,然后递归就好,难点在于子序列初始位置的计算。

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return build(inorder, postorder, 0, 0, inorder.size());
    }
    TreeNode * build(vector<int> &inorder, vector<int> &postorder, int posp, int posi, int len){
        if(len <= 0){return NULL;}
        
        int root_val = postorder[posp + len -1];
        TreeNode * root = new TreeNode(root_val);
        int root_index = 0;
        for(int i = posi ; i < posi + len; ++i){
            if(inorder[i] == root_val){
                root_index = i;
                break;
            }
        }
        root->left = build(inorder, postorder, posp, posi, root_index - posi);
        root->right = build(inorder, postorder, posp + root_index - posi, root_index + 1, len + posi - root_index - 1);
        return root;
    }
};


你可能感兴趣的:(LeetCode: Construct Binary Tree from Inorder and Postorder Traversal)