9. 微软面试题:求二叉树中节点间最大距离
2014-03-08 22:54
417 查看
如果我们把二叉树看成一个图,父子节点间的连线看成是双向的,我们姑且定义“距离”为两节点之间边的个数。
写一个程序,求一颗二叉树中相距最远的两个节点之间的距离。
例如:
二叉树为:
1
/ \
2 3
\
4
/
5
则两点间最大的距离为5
实现如下:
输出结果为:
BSTree's max distance is 5
写一个程序,求一颗二叉树中相距最远的两个节点之间的距离。
例如:
二叉树为:
1
/ \
2 3
\
4
/
5
则两点间最大的距离为5
实现如下:
#include<iostream> using namespace std; struct BSTree{ BSTree(int _v = 0):value(_v),left(NULL),right(NULL) {} int value; BSTree *left; BSTree *right; }; int findMaxEd_num(BSTree *bst, int& max_depth, int &maxed_num) { if(bst == NULL) { max_depth = 0; maxed_num = 0; return 0; } int left_maxdepth = 0; int right_maxdepth = 0; int left_maxednum = 0; int right_maxednum = 0; if(bst->left != NULL) findMaxEd_num(bst->left, left_maxdepth, left_maxednum); if(bst->right != NULL) findMaxEd_num(bst->right, right_maxdepth, right_maxednum); max_depth = left_maxdepth>right_maxdepth?left_maxdepth:right_maxdepth; max_depth += 1; maxed_num = left_maxdepth + right_maxdepth + 1; if(maxed_num < left_maxednum) maxed_num = left_maxednum; if(maxed_num < right_maxednum) maxed_num = right_maxednum; return maxed_num; } int main() { BSTree *root = new BSTree(1); root->left = new BSTree(2); root->right = new BSTree(3); root->left->right = new BSTree(4); root->left->right->left = new BSTree(5); int max_num = 0; int max_depth = 0; cout << "BSTree's max distance is " << findMaxEd_num(root, max_num, max_depth) << endl; return 0; }
输出结果为:
BSTree's max distance is 5
相关文章推荐
- 微软等数据结构+算法面试100题(38)-- 二叉树中任意两个节点间的最大距离
- 微软算法100题11 求二叉树中两节点之间的最大距离
- 微软面试百题010——二叉树节点最大距离
- 二叉树系列——二叉树的最大距离(即相距最远的两个叶子节点,编程之美,百度面试题)
- 【微软100题】求二叉树中节点的最大距离
- <编程之美>经典面试题:求二叉树节点的最大距离(我的解法,最容易理解的版本?)
- 微软面试100题系列---求二叉树中节点的最大距离
- 微软100题第11题(求二叉树中节点的最大距离)
- java面试题:如何求二叉树中节点的最大距离+层序遍历
- 微软面试100道之11 求二叉树中节点的最大距离
- 面试题5:计算二叉树中最大节点到最小节点之间的距离
- 微软面试100题之第11题 求二叉树中节点的最大距离
- 算法与数据结构面试题(11)-求二叉树中节点的最大距离
- 微软算法100道题-----求二叉树中节点的最大距离
- 微软面试100题之11题:求二叉树中节点的最大距离
- 面试题:求二叉树中节点的最大距离
- 微软100题(11) 二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树中节点的最大距离
- 求二叉树的最大叶子节点距离(递归)