您的位置:首页 > 编程语言

leetcode编程记录9 #543 Diameter of Binary Tree

2017-10-27 22:49 375 查看

leetcode编程记录9 #543 Diameter of Binary Tree

标签(空格分隔): leetcode

这次是一道关于树的题目,这是一个比较简单的题目,找出在树中的一条最长的路径的长度。题目如下:

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.

Example:

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].

Note: The length of path between two nodes is represented by the number of edges between them.

题目理解与分析:

这道题目比较简单,只要实现求树的高度的函数,然后在递归调用该函数的过程中,存下最大路径,然后最后得到的就是一条最长路径。

代码如下:

class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
result = 0;
if (root != NULL) {
int example = height(root->left) + height(root->right);
return max(example, result);
} else {
return 0;
}
}
//private:
int result;
int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
int height(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
int left = height(root->left);
int right = height(root->right);
result = max(result, left + right);
return max(left, right) + 1;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: