您的位置:首页 > 其它

The height of binary tree

2012-05-03 19:26 459 查看

The height of binary tree

Time Limit:
1000MS

Memory Limit:
10000K

Description

K, we all know that:

The in-order traversal of a tree prints the left sub-tree, the root, and the right sub-tree.

The pre-order traversal of a tree prints the root, the left sub-tree, and the right sub-tree.

Now I give you some pairs of tree’s in-order traversal and post-order traversal, can you tell me the height of the binary trees? I hope you can.

By the way, each tree’s node name is encoded as a lowercase letter. Obviously, a binary tree will have no more than 26 nodes.

Input

The first line of the input contains a single integer t (1 ≤ t ≤ 10), the number of test cases, followed by the input data for each test case.

Each test case contains two lines, the first line of each test case is the in-order representation of a binary tree, the second line of each test case is the post-order representation of that same binary tree.

Output

For each test case, output one line contains the height of the binary tree in that test case.

Sample Input

2

ABEDFCHG

AEFDBHGC

F

F

Sample Output

4

1

Hint

No hint.

Source

解题代码:

#include <iostream>
#include<cstring>
using namespace std;
class node
{
public:
     char data;
	 node* lc;
	 node* rc;
};

class tree :public node
{
public: 
	tree(string inorder,string postorder)
	{   
		if(inorder.size()==1)
		{
			this->data=inorder[0];
			this->lc=NULL;
			this->rc=NULL;
			return;
		}

		this->data=postorder[inorder.size()-1];
		int p=inorder.find(this->data);
		if(p==0)
			this->lc=NULL;
		else
			this->lc=new tree(inorder.substr(0,p),
			                 postorder.substr(0,p));

		if(p==inorder.size()-1)
			this->rc=NULL;
		else
			this->rc=new tree(inorder.substr(p+1,inorder.size()-1-p),
		                     postorder.substr(p,postorder.size()-1-p));
	}

int height(node* subroot)
{
	if(subroot==NULL)
		return 0;
	int i=height(subroot->lc);
	int j=height(subroot->rc);
	if (i>=j)
		return i+1;
	else 
		return j+1;
}

};

int main()
{
  int n;
  cin>>n;
  for(int i=0;i<n;i++)
  {
	char *post=new char[26];
	char *in=new char[26];
	
	cin>>in;
	cin>>post;
	string post1=(string) post ;
	string in1=(string) in;
    tree* con=new tree(in1,post1);
	cout<<con->height(con)<<endl;
  }

}


另一种解法:不建立树
#include <iostream>
using namespace std;
//Function:GetHeight
int GetHeight(string s1,string s2)
{
	int i=0;
	if(s1.size()==0)
		return 0;
	while(s1[i++]!=s2[s2.size()-1]);
	string t1=s1.substr(0,i-1);
	string t2=s2.substr(0,i-1);
	int m=GetHeight(t1,t2);
	string t3=s1.substr(i,s1.size()-i);
	string t4=s2.substr(i-1,s1.size()-i);
	int n=GetHeight(t3,t4);
	if(m>n)
		return m+1;
	else
		return n+1;		
}

int main() {
	int a;
	cin>>a;
	while(a>0)
	{
		char ch1[26];
		char ch2[26];
		cin>>ch1;
		cin>>ch2;
		string s1=(string)ch1;
		string s2=(string)ch2;
		cout<<GetHeight(s1,s2)<<endl;	
		a--;
	}	
}


欢迎各位大牛指教!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: