题目:如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的。我们定义“距离”为两个节点之间边的条数。写一个程序,求一颗二叉树中相距最远的两个节点之间的距离。
解法:
C++代码如下:
#include<iostream>
using namespace std;
struct node //structure of the node on the binary search tree
{
int value;
node* left;
node* right;
};
struct binary_tree //structure of the binary search tree
{
node* root;
};
void insert(binary_tree& T,int value) //insert node with value 'value' to the binary search tree T
{
if(T.root==NULL) //insert the first node of the binary search tree
{
T.root=(node*)malloc(sizeof(node));
T.root->value=value;
T.root->left=NULL;
T.root->right=NULL;
}
else
{
node* parent=T.root; //parent indicate the parent of the being inserted value
while(true)
{
if(value>parent->value)
{
if(parent->right==NULL)
{
parent->right=(node*)malloc(sizeof(node));
parent->right->value=value;
parent->right->left=NULL;
parent->right->right=NULL;
break;
}
else
{
{
parent=parent->right;
}
}
else if(value<parent->value)
{
if(parent->left==NULL)
{
parent->left=(node*)malloc(sizeof(node));
parent->left->value=value;
parent->left->left=NULL;
parent->left->right=NULL;
break;
}
else
{
parent=parent->left;
}
}
else
{
cout<<"this value has already exist"<<endl;
break;
}
}
}
}
void delete_node(node* root) //delete node binary search tree rooted by 'root'
{
if(root==NULL)
return;
delete_node(root->left); //recursively delete its left subtree
delete_node(root->right); //recursively delete its right subtree
free(root);
}
//delete binary search tree T
void delete_binary_tree(binary_tree& T)
{
delete_node(T.root);
}
int calcu_depth(node* root,int& global_max) //calculate the depth of the binary search tree rooted by 'root', and update the variable global_max the same time
{
if(root==NULL)
return 0;
int local_max;
int left_depth,right_depth;
if(root->left==NULL&&root->right==NULL)
return 0;
else if(root->left==NULL)
{
right_depth=calcu_depth(root->right,global_max);
local_max=right_depth+1;
if(local_max>global_max)
global_max=local_max;
return right_depth+1;
}
else if(root->right==NULL)
{
left_depth=calcu_depth(root->left,global_max);
local_max=left_depth+1;
if(local_max>global_max)
global_max=local_max+1;
return left_depth+1;
}
else
{
left_depth=calcu_depth(root->left,global_max);
right_depth=calcu_depth(root->right,global_max);
local_max=left_depth+right_depth+2;
if(local_max>global_max)
global_max=local_max;
if(left_depth>right_depth)
return left_depth+1;
else
return right_depth+1;
}
}
int find_max_path(node* root) //calculate the max length path between nodes on binary search tree root
{
int global_max=0,max_depth=0;
max_depth=calcu_depth(root,global_max);
return global_max;
}
int main(int* argc,char* argv[])
{
binary_tree B_T;
B_T.root=NULL;
int value;
while(cin>>value)
{
insert(B_T,value);
}
int max_path=find_max_path(B_T.root);
cout<<max_path<<endl;
delete_binary_tree(B_T);
return 0;
}