码迷,mamicode.com
首页 > 其他好文 > 详细

【Construct Binary Tree from Inorder and Postorder Traversal】cpp

时间:2015-05-16 13:12:01      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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 a binary tree node.
 * 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) {
        if ( inorder.size()==0 || postorder.size()==0 ) return NULL;
        return Solution::buildTreeIP(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    static TreeNode* buildTreeIP(
        vector<int>& inorder, 
        int bI, int eI, 
        vector<int>& postorder, 
        int bP, int eP )
    {
        if ( bI > eI ) return NULL;
        TreeNode *root = new TreeNode(postorder[eP]);
        int rootPosInorder = bI;
        for ( int i = bI; i <= eI; ++i )
        {
            if ( inorder[i]==root->val ) { rootPosInorder=i; break; }
        }
        int leftSize = rootPosInorder - bI;
        int rightSize = eI - rootPosInorder;
        root->left = Solution::buildTreeIP(inorder, bI, rootPosInorder-1, postorder, bP, bP+leftSize-1);
        root->right = Solution::buildTreeIP(inorder, rootPosInorder+1, eI, postorder, eP-rightSize, eP-1);
        return root;
    }
};

tips:

思路跟Preorder & Inorder一样。

这里要注意:

1. 算左子树和右子树长度时,要在inorder里面算

2. 左子树和右子树长度可能一样,也可能不一样;因此在计算root->left和root->right的时候,要注意如何切vector下标(之前一直当成左右树长度一样,debug了一段时间才AC)

【Construct Binary Tree from Inorder and Postorder Traversal】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4507596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!