Solution: binary tree problem

Title Description
is now given of a binary sequence preorder traversal sequence preorder, requires you to calculate the height of the binary tree.
Input
Input test data comprising a plurality of sets, each set of input given first positive integer N (<= 50), the total number of nodes in the tree points. 2 has given the following row and the first sequence preorder sequence of length N are no duplicates letters (case sensitive) string.
Output
For each input, output an integer, i.e., the height of the binary tree.
Sample input
. 9
ABDFGHIEC
FDHGIBEAC
. 7
ABCDEFG
gfedcbA
sample output
. 5
. 7
Thinking see Code

#include<bits/stdc++.h>
using namespace std;
int dfs(char*pre,char*in,int n)//n为中序遍历中的查找个数,即为子树的节点数 
{
 if(n==0) return 0;
 int i;
 for(i=0;i<n;i++)    //找顶点 
  if(pre[0]==in[i])
   break;
 int left=dfs(pre+1,in,i);//对左子树
                          //顶点在先序遍历中的位置往后一位
                          //中序查找的起点不变,但结尾处应小于i ,即n=i 
 int right=dfs(pre+i+1,in+i+1,n-i-1);// 对右子树
                                     //顶点在先序遍历中的位置要加上其左子树的全部节点数i,再往后移一位
									 //中序查找的位置就从i往后一位, 其个数为n-i-1; 
 return max(left,right)+1;//要最深的那个 
}
int main()
{
 int n;
 while(cin>>n)
 {
 	char pre[n+1],in[n+1];
 	cin>>pre>>in;
 	cout<<dfs(pre,in,n)<<endl;
 }
 return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43540515/article/details/91868322