Today I did a question to find the maximum distance of the binary tree node, and by the way wrote the next two fork tree establishment, the process of traversal.
I think that the main idea of this problem is deep traversal + dynamic programming, we in the process of deep traversal, for a certain subtree, to find the left and right sub-tree leaf node to the root node maximum distance, and then find the maximum distance through the root node. Finally, we find out the maximum distance of all subtrees through the root node. Is the final result of this topic. The code is as follows:
Binary tree establishment, and traversal//16 8 2-1-1 4-1-1 7 1-1 -1-1 9-1-1 3-1 -1//16 8 2-1-1 4-1-1 7 1-1 -1-1 -1void Build BTree (btreenode* &proot) {int ntemp;cin >> ntemp;if (ntemp = =-1) {proot = NULL;} Else{proot = new Btreenode ();p root->nvalue = ntemp; Buildbtree (Proot->pleft); Buildbtree (Proot->pright);}} void Preorderbtree (btreenode* proot) {if (Proot = = NULL) {return;} cout << proot->nvalue << ""; Preorderbtree (Proot->pleft); Preorderbtree (proot->pright);} void Midorderbtree (btreenode* proot) {if (Proot = = NULL) {return;} Midorderbtree (proot->pleft), cout << proot->nvalue << ""; Midorderbtree (proot->pright);} void Postorderbtree (btreenode* proot) {if (Proot = = NULL) {return;} Postorderbtree (Proot->pleft); Postorderbtree (proot->pright); cout << proot->nvalue << "";} int getmaxnodemaxdistance (btreenode* proot) {if (Proot = = NULL) {return-1;} Yeko node to root node maximum distance int max_left_distance = getmaxnodemaxdistance (proot->pleft);/Right subtree leaf node to root node maximum distance int max_right_distance = getmaxnodemaxdistance (proot->pright);//maximum distance of each subtree node int max_root_ Distance = max_left_distance + max_right_distance + 2;//Compare the maximum distance per subtree node if (max_root_distance > Max_distance) {max_ Distance = max_root_distance;} return max_left_distance > Max_right_distance? max_left_distance+1:max_right_distance+1;} int max_distance = 0;int Main () {btreenode* Root = NULL; Buildbtree (Root), cout << "----------------Build End------------------" << endl;system ("pause") cout < < "Preorderbtree:" << Endl; Preorderbtree (Root), cout << Endl << "midorderbtree:" << Endl; Midorderbtree (Root), cout << Endl << "postorderbtree:" << Endl; Postorderbtree (Root), cout << Endl << "getmaxnodemaxdistance:" << Endl; Getmaxnodemaxdistance (Root), cout << max_distance << endl;system ("pause"); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
About binary tree, establish, traverse, find the maximum distance of the node