https://leetcode-cn.com/problems/diameter-of-binary-tree/
// Problem: LeetCode 543
// URL: https://leetcode-cn.com/problems/maxDiameter-of-binary-tree/
// Tags: Tree DFS Recursion
// Difficulty: Easy
#include <iostream>
#include <algorithm>
using namespace std;
struct TreeNode{
TreeNode* left;
TreeNode* right;
int val;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
class Solution{
private:
int maxDiameter=0;
int depth(TreeNode* root){
// 空节点深度为0
if(root==nullptr)
return 0;
// 左右子树深度
int leftDepth = depth(root->left);
int rightDepth = depth(root->right);
// 更新最大直径
if (leftDepth + rightDepth > this->maxDiameter)
this->maxDiameter = leftDepth + rightDepth;
// 返回该树深度
return max(leftDepth, rightDepth) + 1;
}
public:
int diameterOfBinaryTree(TreeNode* root) {
depth(root);
return this->maxDiameter;
}
};
作者:@臭咸鱼
转载请注明出处:https://www.cnblogs.com/chouxianyu/
欢迎讨论和交流!
原文:https://www.cnblogs.com/chouxianyu/p/13376411.html