[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

1904 ワード

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.
問題解決の考え方:
再帰的な方法で作ることができます.ルートノードは後順ループで決定され、左右のサブツリーは中順ループで決定されます.各サブツリーには、それぞれ後順ループと中順ループがあります.コードは以下の通りです.再帰呼び出し時の位置の計算に注意してください.後順遍歴と中順遍歴の長さは一致します.
/**
 * 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 getTreeNode(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size()-1);
    }
    
    TreeNode *getTreeNode(vector<int> &inorder, int startInOrder, int endInOrder, 
                          vector<int> & postorder, int startPostOrder, int endPostOrder){
        if(startInOrder == endInOrder){
            return new TreeNode(postorder[startPostOrder]);
        }else if(startInOrder > endInOrder){
            return NULL;
        }else{
            int postNumber = postorder[endPostOrder];
            //  postNumber        
            int inPosition=0;
            for(int i=startInOrder; i<=endInOrder; i++){
                if(inorder[i]==postNumber){
                    inPosition=i;
                    break;
                }
            }
            TreeNode* node = new TreeNode(postNumber);
            node->right = getTreeNode(inorder, inPosition+1,endInOrder, postorder, endPostOrder+inPosition-endInOrder, endPostOrder - 1);
            node->left = getTreeNode(inorder, startInOrder, inPosition-1, postorder, startPostOrder, inPosition - 1 - startInOrder + startPostOrder);
            return node;
        }
    }
};