原文链接 [每日 LeetCode] 543. Diameter of Binary Tree
Description:
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 thelongestpath 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.
思路:本题要求二叉树的直径,这里的直径理解为在二叉树中,任意两个节点间最长的路径长度。本题的逻辑不是很好理解,首先需要考虑最长路径可能没有经过根节点,因此需要考虑以下两个方面的问题:
- 最长路径经过根节点:那么根节点的左子树的深度和右子树的深度相加就是我们的结果
- 最长路径没有经过根节点:这个问题就分为两个子问题,分别设置新的根节点为其左子节点和右子节点,然后重复步骤 1
C++ 代码
/**
* 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 d = 1;
diameter(root, d);
return d - 1;
}
int diameter(TreeNode *root, int &d){
if(!root) return 0;
int left = diameter(root->left, d);
int right = diameter(root->right, d);
d = max(d, left + right + 1);
return max(left, right) + 1;
}
};
运行时间:8ms
运行内存:20.1M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于