A problem in the beauty of programming
The solution used in the beauty of programming is an intrusive
The solution is as follows
struct node{node* pleft; Left dial hand tree node* pright; Right sub-tree int nmaxleft; The longest distance in the left dial hand tree is int nmaxright; The longest distance in the right subtree is char chvalue; The value of the node}; int nmaxlen = 0; Look for the longest two-segment distance in the tree void Findmaxlen (node* proot) {//traverse to the leaf node, return if (proot = = NULL) {return; }//If the left dial hand tree is empty, then the maximum distance to the left of the node is 0 if (proot, pleft = = NULL) {proot-nmaxleft = 0; }//If the right subtree is empty, the maximum distance to the right of the node is 0 if (proot-pright = = NULL) {proot-nmaxright = 0; }//If the left dial hand tree is not empty, recursively look for the left subtree longest distance if (Proot-pleft! = NULL) {Findmaxlen (Proot-Pleft); }//If the right subtree is not empty, recursively look for the right subtree longest distance if (Proot-pright! = NULL) {Findmaxlen (Proot-pright); }//Calculates the Zuozi longest node distance if (proot, pleft! = NULL) {int ntempmax = 0; if (Proot, Pleft, Nmaxleft > Proot, Pleft, nmaxright) {Ntempmax = Proot, pLe FT-nmaxleft; } else { Ntempmax = Nmaxright, Pleft, Proot; } proot-Nmaxleft = Ntempmax + 1; }//Calculate right subtree longest node distance if (Proot-pright! = NULL) {int ntempmax = 0; if (Proot, Pright, Nmaxleft > Proot, Pright, nmaxright) {Ntempmax = Proot-P Right-nmaxleft; } else {Ntempmax = Proot, pright, nmaxright; } proot-nmaxright = Ntempmax + 1; }//Update maximum distance if (proot, Nmaxleft + proot, Nmaxright > Nmaxlen) {nmaxlen = Proot-Nmaxlef T + proot-nmaxright; }}
In solving this problem, I think of another algorithm that determines whether a tree is a balanced binary tree, below is my workaround, using the PHP language
Public Function getmaxdistance ($node,& $Max) {if (null = = $node) {return 0;} $left = $this->getmaxdistance ($node->lchild, $Max); $right = $this->getmaxdistance ($node->rchild, $Max); if ($Max < ($left + $right)) {$Max = $left + $right;} Return 1+ ($left > $right? $left: $right);}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Finding the maximum distance of a node in a binary tree