原题链接:543. 二叉树的直径
solution:
dfs+迭代. dfs函数返回以root为根节点的最大深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxd = 0;
int dfs(TreeNode *root){
if(root == nullptr) return 0;
int left = dfs(root->left);
int right = dfs(root->right);
maxd = max(maxd,left + right);
return max(left,right) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return maxd;
}
};