若是咱们把二叉树当作一个图,父子节点之间的连线当作是双向的,node
咱们姑且定义"距离"为两节点之间边的个数。编程
将问题转化为在子树上的解,从而利用动态规划来解决。
spa
typedef struct node { int data; struct node * left; struct node * right; int maxleft; int maxright; }BTree; int maxlen = 0; void FindMaxLen(BTree * root) { int tmp; if(root == NULL) return ; if(root->left == NULL) root->maxleft = 0; if(root->right == NULL) root->maxright = 0; if(root->left != NULL) FindMaxLen(root->left); if(root->right != NULL) FindMaxLen(root->right); if(root->left != NULL) { tmp = (root->left->maxleft > root->left->maxright) ?(root->left->maxleft):(root->left->maxright); root->maxleft = tmp + 1; } if(root->right != NULL) { tmp = (root->right->maxleft > root->right->maxright) ?(root->right->maxleft):(root->right->maxright); root->maxright = tmp + 1; } maxlen = (root->maxleft + root->maxright) > (maxlen) ?(root->maxleft + root->maxright):maxlen; }
感谢 dragon_blog 指出文中的错误,已修改code
参考资料:blog
《编程之美》 电子工业出版社出版 3.8求二叉树中节点的最大距离class