39.
网易有道笔试:
(1).求一个二叉树中任意两个节点间的最大距离,
两个节点的距离的定义是这两个节点间边的个数,
比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,
优化时间空间复杂度。
题目来源:
微软等公司数据结构+算法面试100 题V0.1 版
http://topic.youkuaiyun.com/u/20101126/10/b4f12a00-6280-492f-b785-cb6835a63dc9.html
分析:
最大距离可能一个在左子树,一个在右子树中,通过根节点;也可能出现在左/右子树中,不经过根节点。
通过根节点的最大距离为左右子树深度的和加1;所以可以同时计算树的深度和最大距离。
void FindMaxDis(BSTreeNode *pNode, int &deepth, int &maxdis)
{
if (pNode==NULL)
{
deepth=0;maxdis=0;
return;
}
int l_deepth=0,r_deepth=0;
int l_maxdis=0,r_maxdis=0;
if (pNode->m_pleft)
FindMaxDis(pNode->m_pleft,l_deepth,l_maxdis);
if (pNode->m_pright)
FindMaxDis(pNode->m_pright,r_deepth,r_maxdis);
deepth = (l_deepth > r_deepth ? l_deepth : r_deepth) + 1;
maxdis = l_maxdis > r_maxdis ? l_maxdis : r_maxdis ;
maxdis = (l_deepth+r_deepth) > maxdis ? (l_deepth+r_deepth) : maxdis;
}
int FindMaxDis(BSTreeNode *pNode)
{
int deepth, maxdis;
FindMaxDis(pNode,deepth,maxdis);
return maxdis;
}