Leetcode_Construct Binary Tree from Inorder and Postorder Traversal

用中序遍历和后序遍历的序列确定二叉树,用递归即可。

我写的程序,超出内存限制,原因是对原序列进行多次复制。

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 nullptr;
		}
		auto value=postorder.back();
		TreeNode *root=new TreeNode(value);
		auto it1=find(inorder.begin(),inorder.end(),value);
		vector<int> leftinorder(inorder.begin(),it1);
		vector<int> rightinorder(next(it1),inorder.end());
		auto leftsize=distance(inorder.begin(),it1);
		vector<int> letfpostorder(postorder.begin(),postorder.begin()+leftsize);
		vector<int> rightpostorder(postorder.begin()+leftsize,prev(postorder.end()));
		root->left=buildTree(leftinorder, letfpostorder);
		root->right=buildTree(rightinorder, rightpostorder); 
		return root;
		
    }
};//存储空间占用太多

而网上找到的递归方法,方法类似,但在内存上处理得很好。不需要对序列进行拷贝,直接取位置即可。

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
		return buildTree(begin(inorder),end(inorder),begin(postorder),end(postorder));
        
    }
	template<typename BidiIt> 
	TreeNode* buildTree(BidiIt in_first,BidiIt in_last,BidiIt post_first,BidiIt post_last)
	{
		if(in_first==in_last) return nullptr;
		if(post_first==post_last) return nullptr;
		const auto val=*prev(post_last);
		TreeNode* root=new TreeNode(val);
		auto in_root_pos=find(in_first,in_last,val);
		auto left_size=distance(in_first,in_root_pos);
		auto post_left_last=next(post_first,left_size);
		root->left=buildTree(in_first,in_root_pos,post_first,post_left_last);
		root->right=buildTree(next(in_root_pos),in_last,post_left_last,prev(post_last));
		return root;
	}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值