543.Diameter of Binary Tree¶
Tags: Easy
Tree
Company: Facebook-34, Amazon-13, Microsoft, 字节跳动
Year: 半年内
Links: https://leetcode.com/problems/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.
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.
/**
* 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 {
unordered_map<TreeNode*, int> um;
public:
int diameterOfBinaryTree(TreeNode* root) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
if (!root) return 0;
int leftDepth = 0;
if (root -> left) leftDepth = 1 + maxDepth(root -> left);
int rightDepth = 0;
if (root -> right) rightDepth = 1 + maxDepth(root -> right);
return max(leftDepth + rightDepth, max(diameterOfBinaryTree(root -> left), diameterOfBinaryTree(root -> right)));
}
int maxDepth(TreeNode * root)
{
if (um.find(root) != um.end()) return um[root];
if (!root -> left && !root -> right) {
um[root] = 0;
return 0;
}
int l = 0, r = 0;
if (root -> left) l = maxDepth(root -> left);
if (root -> right) r = maxDepth(root -> right);
um[root] = 1 + max(l, r);
return um[root];
}
};
左子树的最大深度加上右子树的最大深度,然后和左右子树的最大直径比较,用了两次递归,用unordered_map
来存储记录,减少重复计算。
当然也可以只进行一次递归:
/**
* 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 {
unordered_map<TreeNode*, int> um;
int res;
public:
int diameterOfBinaryTree(TreeNode* root) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
maxDepth(root);
return res;
}
int maxDepth(TreeNode * root)
{
if (!root) return 0;
if (um.find(root) != um.end()) return um[root];
int l = maxDepth(root -> left);
int r = maxDepth(root -> right);
res = max(res, l + r);
return (um[root] = 1 + max(l, r));
}
};