数据结构与算法面试题80道(11)

11.求二叉树中节点的最大距离...

如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,

我们姑且定义"距离"为两节点之间边的个数。

写一个程序,

求一棵二叉树中相距最远的两个节点之间的距离。

错误思想:分别找左右子树到根的最深结点,相加。

错误原因:左子树上的左右子树到根的最深结点相加大于根节点左右子树到根的最深结点相加

正确思想:用动态规划来记录结点左右孩子的最大距离。

正确原因:从错误原因可以知道,最大距离为某一结点到它左右孩子的最大距离和

解题方法:(1)某一结点,左孩子为空,它到左孩子的距离为0;右孩子为空,它到右孩子的距离为0;

     (2)若左孩子不为空,该结点左子树的最大距离为:左右子树的最大距离+1;若右孩子不为空,该结点右子树的最大距离为:左右子树的最大距离+1;

     (3)维护最大距离。设置一个全局变量,记录结点左右孩子最大距离和的最大值。

     (4)结果。结果等于最大距离*2。

#include<cstdio>
#include<iostream>
using namespace std;

struct BSTreeNode{
    int mMaxLeft;//左孩子的最长距离
    int mMaxRight;//右孩子的最长距离
    int m_nValue;//value of node
    BSTreeNode *m_pLeft;//left child node
    BSTreeNode *m_pRight;//right child node
};

//建立二叉排序树
void addBSTreeNode(BSTreeNode *&pCurrent,int value){
    //如果当前结点为空,直接插入,如果比当前结点大,插入当前结
    //点的右结点,如果下,插入左结点。如果相等,默认忽略那个值
    //第一个参数的&非常重要。否则需要手动遍历树来找到结点的位置
    if(pCurrent==NULL){
        BSTreeNode *pBSTree=new BSTreeNode();
        pBSTree->mMaxLeft=0;
        pBSTree->mMaxRight=0;
        pBSTree->m_nValue=value;
        pBSTree->m_pLeft=NULL;
        pBSTree->m_pRight=NULL;
        pCurrent=pBSTree;
    }else if(pCurrent->m_nValue>value){
        addBSTreeNode(pCurrent->m_pLeft,value);
    }else if(pCurrent->m_nValue<value){
        addBSTreeNode(pCurrent->m_pRight,value);
    }else{
        cout<<"node repeated,default ignore"<<endl;
    }

}

int mMaxLen=0;//最大值

//穿过根节点,最大距离为ans
void max_distant(BSTreeNode *root){

    if(root==NULL) return;//遍历到叶子结点,返回

    if(root->m_pRight==NULL) root->mMaxRight=0;
    if(root->m_pLeft==NULL) root->mMaxLeft=0;

    if(root->m_pRight!=NULL)//如果右子树为空,最大长度为0,不为空,递归
        max_distant(root->m_pRight);

    if(root->m_pLeft!=NULL)//如果左子树为空,最大长度为0,不为空,递归
        max_distant(root->m_pLeft);

    if(root->m_pLeft!=NULL){//计算左子树最长节点距离
        int mTempMax=0;//临时最大值
        if(root->m_pLeft->mMaxLeft>root->m_pLeft->mMaxRight)
            mTempMax=root->m_pLeft->mMaxLeft;
        else mTempMax=root->m_pLeft->mMaxRight;

        root->mMaxLeft=mTempMax+1;//更新最大值
    }

    if(root->m_pRight!=NULL){//计算右子树最长节点距离
        int mTempMax=0;//临时最大值
        if(root->m_pRight->mMaxLeft>root->m_pRight->mMaxRight)
            mTempMax=root->m_pRight->mMaxLeft;
        else mTempMax=root->m_pRight->mMaxRight;

        root->mMaxRight=mTempMax+1;//更新最大值
    }

    if(root->mMaxLeft+root->mMaxRight>mMaxLen)
        mMaxLen=root->mMaxLeft+root->mMaxRight;
}


int main(){
    BSTreeNode *root=NULL;
    addBSTreeNode(root,10);
    addBSTreeNode(root,6);
    addBSTreeNode(root,13);
    addBSTreeNode(root,5);
    addBSTreeNode(root,11);
    addBSTreeNode(root,3);
    max_distant(root);
    cout<<(mMaxLen<<1)<<endl;
}
原文地址:https://www.cnblogs.com/wabi87547568/p/5263440.html