// ------BTreeMaxNodeLength.cpp------ #include <iostream> using namespace std; template <class T> struct BTNode { // 左孩子 BTNode<T> *lChild; // 右孩子 BTNode<T> *rChild; // 该结点的值 T data; // 左子树最长距离 int leftSubTreeMaxLength; // 右子树最长距离 int rightSubTreeMaxLength; }; template <class T> class BinaryTree { public: void GetMaxNodeLength(BTNode<T> * root, int *maxNodeLength) { // 遍历到叶子结点,返回 if (root == NULL) { return; } // 假设左子树为空,那么该结点左子树最长距离为0 if (root->lChild == NULL) { root->leftSubTreeMaxLength = 0; } // 假设右子树为空,那么该结点右子树最长距离为0 if (root->rChild == NULL) { root->rightSubTreeMaxLength = 0; } // 假设左子树不为空,递归查找左子树最长距离 if (root->lChild != NULL) { GetMaxNodeLength(root->lChild, maxNodeLength); } // 假设右子树不为空,递归查找右子树最长距离 if (root->rChild != NULL) { GetMaxNodeLength(root->rChild, maxNodeLength); } // 计算左子树中距离根结点的最长距离 if (root->lChild != NULL) { if (root->lChild->leftSubTreeMaxLength > root->lChild->rightSubTreeMaxLength) { root->leftSubTreeMaxLength = root->lChild->leftSubTreeMaxLength + 1; } else { root->leftSubTreeMaxLength = root->lChild->rightSubTreeMaxLength + 1; } } // 计算右子树中距离根结点的最长距离 if (root->rChild != NULL) { if (root->rChild->leftSubTreeMaxLength > root->rChild->rightSubTreeMaxLength) { root->rightSubTreeMaxLength = root->rChild->leftSubTreeMaxLength + 1; } else { root->rightSubTreeMaxLength = root->rChild->rightSubTreeMaxLength + 1; } } // 更新最长距离 if (root->leftSubTreeMaxLength + root->rightSubTreeMaxLength > *maxNodeLength) { *maxNodeLength = root->leftSubTreeMaxLength + root->rightSubTreeMaxLength; } } };
时间: 2024-10-09 22:29:40