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 the longest path between any two nodes in a tree. This path may or may not pass through the root.
Analysis:
求二叉树的直径,直径是指二叉树中距离最远的两个结点的距离,不是结点个数。
二叉树问题:都是(先序、中序、后序)遍历+递归,组合拳解决。
开始以为距离最远一定会过根结点,其实不一定。
Solution1:
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (root == NULL)
return 0;
int cur = 0;
int left = 0, cur_left = 0;
int right = 0, cur_right = 0;
// 相当于一根火柴,左边的起点代表这一根
left = GetMaxHeight(root->left);
right = GetMaxHeight(root->right);
cur = left + right;
cur_left = diameterOfBinaryTree(root->left);
cur_right = diameterOfBinaryTree(root->right);
return max(cur, max(cur_left, cur_right));
}
int GetMaxHeight(TreeNode* root) {
if (root == NULL)
return 0;
int left = GetMaxHeight(root->left);
int right = GetMaxHeight(root->right);
return left > right ? (left + 1) : (right + 1);
}
};
Solution2:
解法1中会在求高度时,会有重复的求解,可以用一个map保存已经求出的高度。
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (root == NULL)
return 0;
int cur = GetMaxHeight(root->left) + GetMaxHeight(root->right);
return max(cur, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
}
int GetMaxHeight(TreeNode* root) {
if (root == NULL)
return 0;
if (mp.find(root) != mp.end()) {
return mp[root];
}
int left = GetMaxHeight(root->left);
int right = GetMaxHeight(root->right);
int ret = max(left, right) + 1;
mp[root] = ret;
return ret;
}
private:
unordered_map<TreeNode *, int> mp;
};
Solution3:
在求树的高度时求出直径,同时比较每棵子树的直径和当前最大直径。
class Solution {
private:
int diameter = 0;
public:
int diameterOfBinaryTree(TreeNode* root) {
GetMaxHeight(root);
return diameter;
}
int GetMaxHeight(TreeNode* root) {
if (root == NULL)
return 0;
int left = GetMaxHeight(root->left);
int right = GetMaxHeight(root->right);
// left+right 相当于一根火柴,左边的起点代表这一根
diameter = max(diameter, left + right);
return max(left, right) + 1;
}
};
Reference:
[1] https://my.oschina.net/liyurong/blog/1503784
本文深入探讨了二叉树直径的计算问题,提供三种不同的解决方案,包括直接计算、使用哈希表避免重复计算和在求高度过程中计算直径。通过递归和遍历技巧,有效地解决了距离最远节点对的问题。
418

被折叠的 条评论
为什么被折叠?



