*Leetcode_construct-binary-tree-from-inorder-and-postorder-traversal

地址: http://oj.leetcode.com/problems/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.

思路:可参考上一题:http://blog.csdn.net/flyupliu/article/details/22864057(根据先序和中序确定树)
先序和中序来确定树应该比后序和中序来确定树难一点,因为根的position要算出来。而后序和中序中,只要先创建右子树,再创建左子树,那么根就一直是后序数组的最后一个值。
这一题和上一题都跑了170ms到180ms。应该会有更简明高效的方法。
参考代码:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 vector<int> invec, postvec;
 TreeNode* construct_tree(int left, int right)
 {
     if(left>right || postvec.empty())
         return NULL;
     int root_val = postvec.back();
     TreeNode* p = new TreeNode(root_val);
     postvec.pop_back();
     if(left==right)
         return p;
     int root_index = 0;
     for(; root_index < invec.size(); ++root_index)
         if(invec[root_index]==root_val)
             break;
     if(root_index==left)
     {
         p->right = construct_tree(left+1, right);
     }
     else if(root_index==right)
     {
         p->left = construct_tree(left, right-1);
     }
     else
     {
         p->right = construct_tree(root_index+1, right);
         p->left = construct_tree(left, root_index-1);
     }
     return p;
 }
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if(inorder.empty())
            return NULL;
        invec = inorder;
        postvec = postorder;
        return construct_tree(0, invec.size()-1);
    }
};


  
  
//SECOND TRIAL, 116ms
class Solution {
private :
     TreeNode * construct ( int in [], int post [], int len )
     {
         if ( len <= 0 )
             return NULL ;
         int root_val = post [ len - 1 ];
         TreeNode * root = new TreeNode ( root_val );
         int offset = 0 ;
         while ( offset < len && in [ offset ] != root_val )
             ++ offset ;
         root -> left = construct ( in , post , offset );
         root -> right = construct ( in + offset + 1 , post + offset , len - 1 - offset );
         return root ;
     }
public :
     TreeNode * buildTree ( vector < int > & inorder , vector < int > & postorder ) {
         if ( inorder . empty ())
             return NULL ;
         int * in = & inorder [ 0 ], * post = & postorder [ 0 ];
         return construct ( in , post , inorder . size ());
     }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值