本文主要是介绍Diameter of Binary Tree问题及解法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
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);}
};
这篇关于Diameter of Binary Tree问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!