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

来源:互联网 发布:美国网络中立 编辑:程序博客网 时间:2024/06/08 00:39

递归解法:

(1)如果二叉树为空,返回0,同时记录左子树和右子树的深度,都为0

(2)如果二叉树不为空,最大距离要么是左子树中的最大距离,要么是右子树中的最大距离,要么是左子树节点中到根节点的最大距离+右子树节点中到根节点的最大距离,同时记录左子树和右子树节点中到根节点的最大距离。



intGetMaxDistance(BinaryTreeNode* pRoot,int& maxLeft,int& maxRight)

{

    //maxLeft, 左子树中的节点距离根节点的最远距离

    //maxRight, 右子树中的节点距离根节点的最远距离

    if(pRoot== NULL)

    {

        maxLeft =0;

        maxRight =0;

        return0;

    }

    int maxLL, maxLR, maxRL, maxRR;

    int maxDistLeft, maxDistRight;

    if(pRoot->m_pLeft!= NULL)

    {

        maxDistLeft=GetMaxDistance(pRoot->m_pLeft, maxLL, maxLR);

        maxLeft = max(maxLL, maxLR)+1;

    }

    else

    {

        maxDistLeft=0;

        maxLeft =0;

    }

    if(pRoot->m_pRight!= NULL)

    {

        maxDistRight=GetMaxDistance(pRoot->m_pRight, maxRL, maxRR);

        maxRight = max(maxRL, maxRR)+1;

    }

    else

    {

        maxDistRight=0;

        maxRight =0;

    }

    return max(max(maxDistLeft,maxDistRight), maxLeft+maxRight);

}


0 0
原创粉丝点击