------BTreeMaxNodeLength.cpp------#include <iostream>using namespace Std;template <class t>struct btnode{//left child btnode<t> *lchild;//right child btnode<t> *rchild;//The value of the node T data;//Zuozi maximum distance int leftsubtreemaxlength;/ /right subtree maximum distance int rightsubtreemaxlength;}; Template <class t>class binarytree{public:void getmaxnodelength (btnode<t> * root, int *maxnodelength) {// Traverse to leaf node, return if (root = = NULL) {return;} Assuming that the left subtree is empty, the maximum distance of the left subtree of the node is 0if (root->lchild = = NULL) {root->leftsubtreemaxlength = 0;} Assuming that the right subtree is empty, the maximum distance to the right subtree of the node is 0if (root->rchild = = NULL) {root->rightsubtreemaxlength = 0;} Suppose the left subtree is not empty, recursively finds Zuozi longest distance if (root->lchild! = NULL) {getmaxnodelength (root->lchild, maxnodelength);} Assuming that the right subtree is not empty, recursively finds the right subtree longest distance if (root->rchild! = NULL) {getmaxnodelength (root->rchild, maxnodelength);} Calculates the longest distance from the root node in the left subtree if (root->lchild! = NULL) {if (Root->lchild->leftsubtreemaxlength > root->lchild- >rightsubtreemaxlength) {root->leftsubtreemaxlength = Root->lchild->lefTsubtreemaxlength + 1;} Else{root->leftsubtreemaxlength = Root->lchild->rightsubtreemaxlength + 1;}} Calculates the longest distance from the root node in the right subtree if (root->rchild! = NULL) {if (Root->rchild->leftsubtreemaxlength > root->rchild- >rightsubtreemaxlength) {root->rightsubtreemaxlength = root->rchild->leftsubtreemaxlength + 1;} Else{root->rightsubtreemaxlength = Root->rchild->rightsubtreemaxlength + 1;}} Update maximum distance if (Root->leftsubtreemaxlength + root->rightsubtreemaxlength > *maxnodelength) {*maxnodelength = Root->leftsubtreemaxlength + root->rightsubtreemaxlength;}}};
Data structure-Find the maximum distance (c + +) of nodes in a binary tree