任意一棵二叉树中最大距离的两个节点【算法】

 //具体的实现方法:
void findMaxLength(Node* root){
     if(root==NULL) return;
     //如果左子树为空,则该节点左边最长距离为0 
     if(root->left==NULL) 
         root->maxLeft=0;
     //如果右子树为空,则该节点右边最长距离为0 
     if(root->right==NULL) 
         root->maxRight=0;
     //如果左子树不为空,递归寻找左边最长距离 
     if(root->left!=NULL) 
         findMaxLength(root->left);
     //如果右子树不为空,递归寻找右边最长距离 
     if(root->right!=NULL) 
         findMaxLength(root->right);
     //计算左子树最长节点距离 
     if(root->left!=NULL) 
     {
         int tempMax=0;
         if(root->left->maxLeft > root->left->maxRight)
           tempMax=root->left->maxLeft;
         else tempMax=root->left->maxRight;
         root->maxLeft=tempMax+1;
     }
     //计算油子树最长节点距离 
     if(root->right!=NULL) 
     {
         int tempMax=0;
         if(root->right->maxLeft > root->right->maxRight)
           tempMax=root->right->maxLeft;
         else tempMax=root->right->maxRight;
         root->maxRight=tempMax+1;
     }
     //更新最长距离 
     if(root->maxLeft+root->maxRight > maxLen)
       maxLen=root->maxLeft+root->maxRight;
}

你可能感兴趣的:(null)