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.
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.
solution
实为求树的高度
深度优先搜索即可
/**
* 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 max_diameter = 0;
int diameterOfBinaryTree(TreeNode* root) {
len(root);
return max_diameter;
}
int len(TreeNode * root)
{
//最长路径节点个数
if (root == NULL)
return 0;
else
{
int tmp = len(root->left);
int tmp2 = len(root->right);
if (tmp + tmp2 > max_diameter)
max_diameter = tmp + tmp2;
return 1 + (tmp > tmp2 ? tmp : tmp2);
}
}
};
分析:
时间复杂度O(N):每个节点我都要访问一次
空间复杂度O(N):len函数递归调用N次
没想到用一个变量来保存结果,使用队列来遍历树
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
queue<TreeNode*> q;
int diameter = 0;
if (root)
q.push(root);
while (!q.empty()) {
TreeNode *tmp = q.front();
q.pop();
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
int now = len(tmp->left) + len(tmp->right);
if (now > diameter)
diameter = now;
}
return diameter;
}
int len(TreeNode * root)
{
//最长路径节点个数
if (root == NULL)
return 0;
else
{
int tmp = len(root->left);
int tmp2 = len(root->right);
return 1 + (tmp > tmp2 ? tmp : tmp2);
}
}
};