您的位置:首页 > 其它

leetcode106. Construct Binary Tree from Inorder and Postorder Traversal

2018-02-25 15:37 417 查看
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int postLength = postorder.size();

        int inLength  = inorder.size();

        return buildTree(postorder,0,postLength - 1,inorder,0,inLength-1);
    }
    
    TreeNode* buildTree(vector<int>& preorder,int preStart,int preEnd, vector<int>& inorder,int inStart,int inEnd) {
        if(preStart>preEnd || inStart>inEnd) return NULL;
int rootVal =preorder[preEnd];
int rootindex = inStart;
for(int i = inStart;i<=inEnd;i++){
            if(rootVal == inorder[i] ){
                rootindex = i;
                break;
            }
        }
cout<<rootindex<<endl;
        TreeNode *root = new TreeNode(rootVal);
        int length = rootindex - inStart;
cout<<preStart+1<<preStart + length<<inStart<<rootindex - 1<<endl;
cout<<preStart + length + 1<<preEnd<<rootindex + 1<<inEnd<<endl;
        

root->left = buildTree(preorder,preStart,preStart+length-1,inorder,inStart,rootindex - 1);

root->right = buildTree(preorder,preStart+length,preEnd-1,inorder,rootindex + 1,inEnd);
        
        return root;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐