543. Diameter of Binary Tree
https://leetcode.com/problems/diameter-of-binary-tree/description/
Thoughts
Code
/*
* @lc app=leetcode id=543 lang=cpp
*
* [543] Diameter of Binary Tree
*/
// @lc code=start
/**
* 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 {
public:
int res = 0;
int dfs(TreeNode *cur) {
if (cur == nullptr) return 0;
int l = dfs(cur->left);
int r = dfs(cur->right);
res = max(res, l + r);
return max(l, r) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return res;
}
};
// @lc code=end
Analysis
Ver.2
Last updated