diff options
author | crupest <crupest@outlook.com> | 2021-02-23 17:36:58 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2021-02-23 17:36:58 +0800 |
commit | b0162802ad9723c678e495f29ca2f0fc0af2eff1 (patch) | |
tree | 535f50340d5e0768e06df6fcdfebdb83a72cdabf | |
parent | 80533bf9bc73a0b3db3609b5a0192a68d898e6f0 (diff) | |
download | solutions-b0162802ad9723c678e495f29ca2f0fc0af2eff1.tar.gz solutions-b0162802ad9723c678e495f29ca2f0fc0af2eff1.tar.bz2 solutions-b0162802ad9723c678e495f29ca2f0fc0af2eff1.zip |
Add problem 543.
-rw-r--r-- | cpp/543.cpp | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/cpp/543.cpp b/cpp/543.cpp new file mode 100644 index 0000000..f782521 --- /dev/null +++ b/cpp/543.cpp @@ -0,0 +1,32 @@ +struct TreeNode {
+ int val;
+ TreeNode *left;
+ TreeNode *right;
+ TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
+};
+
+#include <algorithm>
+
+class Solution {
+public:
+ int diameterOfBinaryTree(TreeNode *root) {
+ int max = 0;
+ depth(root, max);
+ return max;
+ }
+
+ static int depth(TreeNode *root, int &max) {
+ if (root == nullptr)
+ return -1;
+
+ auto left = depth(root->left, max) + 1;
+ auto right = depth(root->right, max) + 1;
+
+ auto current_max = left + right;
+ if (current_max > max) {
+ max = current_max;
+ }
+
+ return std::max(left, right);
+ }
+};
|