题目:求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,优化时间空间复杂度。 看了那么多网上的答案,总觉得有点复杂,自己写了一个,欢迎指正 #define max(a,b) a>b?a:b typedef struct BinTreeNode { int data; struct BinTreeNode *pLeft; struct BinTreeNode *pRight; }*pBinTreeNode; int GetDeepNode(BinTreeNode* node) { int k = 0; if(NULL!=node->pLeft|| NULL!=node->pRight) { int left=0; int right =0; if(NULL!=node->pLeft) left = GetDeepNode(node->pLeft)+1; if(NULL!=node->pRight) right = GetDeepNode(node->pRight)+1; k= max(left,right); } return k; } int MaxDis(BinTreeNode* root) { int fatherMax=0; if(NULL!=root) fatherMax = GetDeepNode(root); int leftLen=0; int rightLen =0; if(NULL!=root->pLeft) leftLen = GetDeepNode(root->pLeft)+1; if(NULL!=root->pRight) rightLen = GetDeepNode(root->pRight)+1; int childMax = leftLen+rightLen; return max(fatherMax,childMax); } int main() { int preOrder[]={10,6,4,7,1,5,8,14,12,16}; int inOrder[]={1,7,4,5,6,8,10,12,14,16}; int len = sizeof(preOrder)/sizeof(int); BinTreeNode* root= CreateBinTree(preOrder,inOrder,len);//根据前序和中序构建二叉树 int maxDistance = MaxDis(root); cout<<maxDistance<<endl; }