LeetCode 543. Diameter of Binary Tree
Woodyiiiiiii opened this issue · comments
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.
这是一道树形DP的Easy难度的题目,是求二叉树最长路径和的简化版,求二叉树最长路径长度。
class Solution {
int diameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
getDiameter(root, 1);
return diameter;
}
public int getDiameter(TreeNode node, int l) {
if (node == null) {
return l - 1;
}
int left = getDiameter(node.left, l + 1);
int right = getDiameter(node.right, l + 1);
diameter = Math.max(diameter, left - l + right - l);
return Math.max(left, right);
}
}
需要求最长路径长度,就是要求两个节点的最大高度之差。
需要注意一点,当遍历到null时,返回的是当前高度减一(l - 1),即当前根节点的高度,分析一下就能明白了。
大佬的做法更清晰,:
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
maxDepth(root, res);
return res;
}
int maxDepth(TreeNode* node, int& res) {
if (!node) return 0;
int left = maxDepth(node->left, res);
int right = maxDepth(node->right, res);
res = max(res, left + right);
return max(left, right) + 1; // 最大路径+1,回溯
}
};
从0开始,每次回溯都+1。
其实还可以用哈希表优化,记录每次遍历过的值,防止重复遍历:
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
maxDepth(root, res);
return res;
}
int maxDepth(TreeNode* node, int& res) {
if (!node) return 0;
if (m.count(node)) return m[node];
int left = maxDepth(node->left, res);
int right = maxDepth(node->right, res);
res = max(res, left + right);
return m[node] = (max(left, right) + 1);
}
private:
unordered_map<TreeNode*, int> m;
};
参考资料:
LeetCode原题