zoukankan      html  css  js  c++  java
  • 数据结构

    // ------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;
    		}
    	}
    };

  • 相关阅读:
    基本數據類型
    5月28号 垃圾回收机制
    5月28 基本运算符
    5月30日 循环之while循环
    5月28号 与用户交互
    5月31日 基本数据类型(列表类型 字典类型 元组)及其内置方法
    5月30号 基本数据类型(整数型 字符串类型)及其内置方法
    變量
    5月29日 学习笔记 可变不可变类型 成员运算符和身份运算符 条件 流程控制之if判断
    关于Flash CS4字体不能加粗的问题[附解决方法]
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5328600.html
Copyright © 2011-2022 走看看