二叉树的直径:二叉树中从一个结点到另一个节点最长的路径,叫做二叉树的直径
采用分治和递归的思想:
根节点为root的二叉树的直径 = max(root->left的直径,root->right的直径,root->left的最大深度+root->right的最大深度+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 {
private:
int res=0; //记录最大直径
int depth(TreeNode* root){ //求树的高度,同时计算这个节点的直径,更新最大直径
if(!root)
return 0;
int l=depth(root->left);
int r=depth(root->right);
res=max(res,l+r); //res为当前最大直径
return max(l,r)+1;
}
public:
int diameterOfBinaryTree(TreeNode* root) {
depth(root);
return res;
}
};