首页 > 其他 > 详细

9. 微软面试题:求二叉树中节点间最大距离

时间:2014-03-09 00:58:47      阅读:481      评论:0      收藏:0      [点我收藏+]

如果我们把二叉树看成一个图,父子节点间的连线看成是双向的,我们姑且定义“距离”为两节点之间边的个数。


写一个程序,求一颗二叉树中相距最远的两个节点之间的距离。

例如:

二叉树为:

       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


9. 微软面试题:求二叉树中节点间最大距离,布布扣,bubuko.com

9. 微软面试题:求二叉树中节点间最大距离

原文:http://blog.csdn.net/hhh3h/article/details/20803081

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!