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.
题意
思路1
一条路径的长度为该路径经过的节点数减一,所以求直径(即求路径长度的最大值)等效于求路径经过节点数的最大值减一
我们定义一个递归函数 depth(node)
计算 ,函数返回该节点为根的子树的深度。先递归调用左儿子和右儿子求得它们为根的子树的深度 L
和 R
,则该节点为根的子树的深度即为max(L,R)+1
该节点的值为 L+R+1
递归搜索每个节点并设一个全局变量 ans
记录 的最大值,最后返回 ans-1
即为树的直径。
代码1
/**
* 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 {
int ans = 0; // 全局最优
int dfs(TreeNode *root)
{
if(root == NULL) return 0;
int l = dfs(root->left);
int r = dfs(root->right);
ans = max(ans, l + r);
return max(l, r) + 1; // 每棵子树最大
}
public:
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return ans;
}
};
class Solution {
int ans;
int depth(TreeNode* rt){
if (rt == NULL) return 0; // 访问到空节点了,返回0
int L = depth(rt->left); // 左儿子为根的子树的深度
int R = depth(rt->right); // 右儿子为根的子树的深度
ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans
return max(L, R) + 1; // 返回该节点为根的子树的深度
}
public:
int diameterOfBinaryTree(TreeNode* root) {
ans = 1;
depth(root);
return ans - 1;
}
};