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

  • 相关阅读:
    (转)基于MapWinGis开发探索(一)
    ArcGIS Server REST API开发相关新词汇
    自写地图全图功能
    向远程目录写数据
    GetUpperBound方法
    监控安装教程
    办公室局域网打印机共享设置
    电脑Bois中usb模式启动热键
    SQL SERVER 2005无法远程连接
    用网线直接把打印机连入网络的问题
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5328600.html
Copyright © 2011-2022 走看看