Diameter of Binary Tree问题及解法

来源:互联网 发布:数据库笛卡尔积运算 编辑:程序博客网 时间:2024/05/20 23:05

问题描述:

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

示例:

Given a binary tree 

          1         / \        2   3       / \           4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

问题分析:

求解该问题实际是就是求解树的深度问题,两棵子树深度求解完成,相应的的答案也就出来了。


过程详见代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int diameterOfBinaryTree(TreeNode* root) {        int diameter = 0;        height(root, diameter);        return diameter;    }private:    int height(TreeNode* node, int& diameter) {        if (!node) {            return 0;        }        int lh = height(node->left, diameter);        int rh = height(node->right, diameter);        diameter = max(diameter, lh + rh);        return 1 + max(lh, rh);    }};


0 0
原创粉丝点击