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

leetCode(18):Construct Binary Tree from Preorder and Inorder (Inorder and Postorder) Traversal

时间:2015-06-22 09:56:49      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:二叉树   leetcode   

Given preorder and inorder (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>& preorder,int from1,int to1,
					vector<int>& inorder,int from2,int to2)
    {
    	if(from1>to1)
    		return NULL;
    	int i=from2;
    	for(;i<=to2;++i)
    	{
    		if(inorder[i]==preorder[from1])
    			break;
    	}
    	TreeNode* root=new TreeNode(inorder[i]);
    	root->left=buildTree(preorder,from1+1,from1+i-from2,inorder,from2,i-1);
    	root->right=buildTree(preorder,from1+i-from2+1,to1,inorder,i+1,to2);
    	return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
};

已知中序和后序,构建二叉树:

/**
 * 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,int from1,int to1,
					vector<int>& postorder,int from2,int to2)
    {
    	if(from1>to1)
    		return NULL;
    	// if(from1==to1)
    	// {
    		// TreeNode* tmp=new TreeNode(inorder[from1]);
    		// return tmp;
    	// }
    	
    	int i=from1;
    	for(;i<=to1;++i)
    	{
    		if(inorder[i]==postorder[to2])
    			break;
    	}
    	TreeNode* root=new TreeNode(inorder[i]);
    	root->left=buildTree(inorder,from1,i-1,postorder,from2,from2+i-from1-1);
    	root->right=buildTree(inorder,i+1,to1,postorder,from2+i-from1,to2-1);
    	return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        	return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
};


leetCode(18):Construct Binary Tree from Preorder and Inorder (Inorder and Postorder) Traversal

标签:二叉树   leetcode   

原文地址:http://blog.csdn.net/walker19900515/article/details/46591235

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