#include<iostream>using namespace std ;class Node {public:char ch ;Node * left ;Node * right ;Node ( char c , Node * lc , Node * rc ) {ch = c ;left = lc ;right = rc ;}Node () {}~ Node () {delete left ;delete right ;}};//create a tree refer to the inorder and postorderNode * create ( char * inorder , char * postorder , int length ) {if ( length == 0 ) {return NULL ;} else {Node * node = new Node ;node -> ch = postorder [ length - 1 ];int rootIndex = 0 ;for (; rootIndex < length ; rootIndex ++ ) {if ( inorder [ rootIndex ] == postorder [ length - 1 ]) {break ;}}node -> left = create ( inorder , postorder , rootIndex );node -> right = create ( rootIndex + inorder + 1 , postorder + rootIndex ,length - rootIndex - 1 );return node ;}}//return the height of a binary treeint getHeight ( Node * root ) {if ( root == NULL ) {return 0 ;} elsereturn 1 + max ( getHeight ( root -> left ), getHeight ( root -> right ));}int main () {char inorder [ 27 ];char postorder [ 27 ];int count ;Node * root ;int length ;cin >> count ;while ( count > 0 ) {cin >> inorder ;cin >> postorder ;length = strlen ( postorder );cout << "Start creating..." << endl ;cout << "The height of the tree is : "<< getHeight ( create ( inorder , postorder , length )) << endl ;count -- ;}}
根据二叉树的中序遍历和后序遍历创建 一棵二叉树,并且返回所创建的树的树高,具体方法请参见下面源码(经过调试,无任何bug存在)
最新推荐文章于 2022-04-18 00:03:37 发布