Leetcode 树-543-二叉树的直径
作者:互联网
DFS解法
/**
* 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 max_len = 0;
public:
int dfs(TreeNode* root) {
// 叶节点返回深度0
int right = (root->left != nullptr) ? dfs(root->left) : 0;
int left = (root->right != nullptr) ? dfs(root->right) : 0;
int depth = max(left, right) + 1;
if (left + right > max_len)
max_len = left + right;
return depth;
}
int diameterOfBinaryTree(TreeNode* root) {
if (root == nullptr) return 0;
dfs(root);
return max_len;
}
};
标签:right,TreeNode,int,max,543,二叉树,root,Leetcode,left 来源: https://blog.csdn.net/SL_World/article/details/114300280