问题来源:《编程之美》3.8 求二叉树节点的最大距离
如果把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两个节点之间的个数。
写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
如下图所示,粗箭头的边表示最长距离:
树中相距最远的两个节点是A, B
1 #include<iostream> 2 using namespace std; 3 typedef struct BiTNode 4 { 5 BiTNode *left; 6 BiTNode *right; 7 }BiTNode, *BiTree; 8 9 int maxDis = 0; 10 11 void createTree(BiTree &root) 12 { 13 BiTree left1 = new(BiTNode); 14 BiTree right1 = new(BiTNode); 15 16 left1->left = NULL; 17 left1->right = NULL; 18 right1->left = NULL; 19 right1->right = NULL; 20 21 root->left = left1; 22 root->right = right1; 23 24 25 BiTree left2 = new(BiTNode); 26 left2->left = NULL; 27 left2->right = NULL; 28 BiTree right2 = new(BiTNode); 29 right2->left = NULL; 30 right2->right = NULL; 31 left1->left = left2; 32 left1->right = right2; 33 34 BiTree left3 = new(BiTNode); 35 left3->left = NULL; 36 left3->right = NULL; 37 BiTree right3 = new(BiTNode); 38 right3->left = NULL; 39 right3->right = NULL; 40 left2->left = left3; 41 left2->right = right3; 42 } 43 44 void deleteTree(BiTree root) 45 { 46 if(root) 47 { 48 deleteTree(root->left); 49 deleteTree(root->right); 50 delete(root); 51 root = NULL; 52 } 53 } 54 55 int height(BiTree root) 56 { 57 if(root == NULL) 58 return 0; 59 else 60 return height(root->left) > height(root->right) ? height(root->left) + 1 : height(root->right) + 1; 61 } 62 63 int max(int a, int b, int c) 64 { 65 int tmp = a > b ? a : b; 66 return tmp > c ? tmp : c; 67 } 68 69 int treeDistance(BiTree root) 70 { 71 if(root == NULL) 72 return 0; 73 else if(root->left == NULL && root->right == NULL) 74 return 0; 75 int dis = max(height(root->left) + height(root->right), treeDistance(root->left), treeDistance(root->right)); 76 if(maxDis < dis) 77 maxDis = dis; 78 return dis; 79 } 80 81 int main() 82 { 83 BiTree root = new(BiTNode); 84 root->right = root->left = NULL; 85 createTree(root); 86 cout << "height:" << height(root) << endl; 87 cout << "treeDistance:" << treeDistance(root) << endl; 88 cout << "_____________________" << endl; 89 deleteTree(root); 90 }