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

先序+中序和中序+后序建树

时间:2014-08-11 21:37:42      阅读:504      评论:0      收藏:0      [点我收藏+]

标签:建二叉树   二叉树遍历   leetcode   递归   

思路:先序的第一个元素和后序的最后一个元素是当前子树的根,然后遍历中序序列,找到左右子树的分界线,递归建左子树和右子树。

class Solution {
public:
    /*由于是oj,这里假设给的序列是合法的,正常情况是需要判断不合法情况的 */
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder,int instart,int inend,int poststart,int postend) {
    	TreeNode* root = new TreeNode(postorder[postend]);
    	if(instart == inend && poststart == postend && instart == poststart)return root;
    	int i;
    	for(i = instart;i <= inend;++i)
    	{
    		if(inorder[i] == postorder[postend])break;//找到中序的根节点
    	}
    	if(i > instart)root -> left = buildTree(inorder,postorder,instart,i - 1,poststart,poststart + (i - instart - 1));
    	if(i < inend) root -> right = buildTree(inorder,postorder,i + 1,inend,poststart + i - instart,postend - 1);
    	return root;
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    	int inlength = inorder.size(),postlength = postorder.size();
    	if( inlength == 0 || inlength != postlength ) return NULL;
    	return buildTree(inorder,postorder,0,inlength-1,0,postlength-1);
    }
};

class Solution {
public:
    TreeNode *buildTree(vector<int>& preorder,vector<int> &inorder,int prestart,int preend,int instart,int inend) {
    	TreeNode* root = new TreeNode(preorder[prestart]);
    	if(instart == inend && prestart == preend && instart == prestart)return root;
    	int i;
    	for(i = instart;i <= inend;++i)
    	{
    		if(inorder[i] == preorder[prestart])break;//找到中序的根节点
    	}
    	if(i > instart)root -> left = buildTree(preorder,inorder,prestart+1,prestart + i - instart,instart,i - 1);
    	if(i < inend) root -> right = buildTree(preorder,inorder,prestart + i - instart + 1,preend,i + 1,inend);
    	return root;
    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    	int prelength = preorder.size(),inlength = inorder.size();
    	if( inlength == 0 || inlength != prelength ) return NULL;
    	return buildTree(preorder,inorder,0,prelength-1,0,inlength-1);
    }
};


先序+中序和中序+后序建树,布布扣,bubuko.com

先序+中序和中序+后序建树

标签:建二叉树   二叉树遍历   leetcode   递归   

原文地址:http://blog.csdn.net/fangjian1204/article/details/38496567

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