Leetcode 543. 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.
题目大意:
查找二叉树中两个结点间的最长距离,该距离可能不经过根结点。
解题思路:
根据“两个结点间最长距离”在题中的定义,观察可知,如果该距离经过根结点,则两个结点间的最长距离为根结点左右子结点深度之和。如果该距离不经过根结点,则需求出分别以根结点左右子结点的两个结点间的最长距离,再将这三个值进行比较取最大值即可。
代码1:
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
depth(root, res);
return res;
}
int depth(TreeNode* root, int &res){
if(!root)
return 0;
int left = depth(root->left, res);
int right = depth(root->right, res);
res = max(left + right, res);
return max(left, right) + 1;
}
};
代码2 (用哈希表储存优化加速):
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int res = 0;
depth(root, res);
return res;
}
int depth(TreeNode* root, int &res){
if(!root)
return 0;
if(m.count(root))
return m[root];
int left = depth(root->left, res);
int right = depth(root->right, res);
res = max(left + right, res);
return m[root] = (max(left, right) + 1);
}
private:
unordered_map<TreeNode*, int> m;
};
本文探讨了LeetCode上543题二叉树直径的解决方案,详细介绍了如何寻找二叉树中两个节点间的最长路径,无论路径是否通过根节点。通过递归深度遍历的方法,结合左右子树深度之和的最大值,实现了高效的求解。代码提供了两种实现方式,包括使用哈希表进行优化。
441

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



