Added C++ code for Diameter of Binary Tree (#257)

* Adding code of Diameter of Binary Tree for Cpp

* Update README.md
This commit is contained in:
Arshdeep Singh 2021-10-02 15:42:07 +05:30 committed by GitHub
parent b1e0be88fe
commit 0c2f6dad3a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 1 deletions

View File

@ -216,7 +216,7 @@ LeetCode
|572|[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) | [Python](./algorithms/python/SubtreeOfAnotherTree/isSubtree.py)|Easy|
|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [Python](./algorithms/python/BinaryTreeTilt/findTilt.py)|Easy|
|547|[Friend Circles](https://leetcode.com/problems/friend-circles/) | [C++](./algorithms/cpp/friendCircles/FriendCircles.cpp)|Medium|
|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy|
|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./algorithms/cpp/diameterOfBinaryTree/diameterOfBinaryTree.cpp), [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy|
|538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [Python](./algorithms/python/ConvertBSTtoGreaterTree/convertBST.py)|Easy|
|532|[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) | [Python](./algorithms/python/K-diffPairsInAnArray/findPairs.py)|Easy|
|520|[Detect Capital](https://leetcode.com/problems/detect-capital/) | [C++](./algorithms/cpp/detectCapital/DetectCapital.cpp)|Easy|

View File

@ -0,0 +1,31 @@
// Source : https://leetcode.com/problems/add-and-search-word-data-structure-design/
// Author : Arshdeep Singh
// Date : 2021-10-01
/**
* 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 {
private:
int diameter;
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
diameter = max(diameter, left + right);
return 1 + max(left, right);
}
public:
int diameterOfBinaryTree(TreeNode* root) {
diameter = 0;
maxDepth(root);
return diameter;
}
};