Maximum Depth of Binary Tree Solutions in C++
Number 104
Difficulty Easy
Acceptance 66.1%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/// Author : Hao Chen// Date : 2014-06-21/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:int maxDepth(TreeNode *root) {if (root==NULL){return 0;}if (!root->left && !root->right){return 1;}int left=1, right=1;if (root->left){left += maxDepth(root->left);}if (root->right){right += maxDepth(root->right);}return left>right?left:right;}};class Solution2 {public:int maxDepth(TreeNode *root) {if (root==NULL) return 0;return max(maxDepth(root->left), maxDepth(root->right)) + 1;}};
C++ solution by pezy/LeetCode
/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:int maxDepth(TreeNode *root) {if (root == NULL) return 0;return std::max(maxDepth(root->left), maxDepth(root->right))+1;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/description//// Author : liuyubobobo/// Time : 2017-11-17#include <iostream>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Recursive/// Time Complexity: O(n), where n is the nodes' number in the tree/// Space Complexity: O(h), where h is the height of the treeclass Solution {public:int maxDepth(TreeNode* root) {if(root == NULL)return 0;return 1 + max(maxDepth(root->left), maxDepth(root->right));}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/description//// Author : liuyubobobo/// Time : 2017-11-17#include <iostream>#include <stack>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Non-recursive/// Time Complexity: O(n), where n is the nodes' number in the tree/// Space Complexity: O(h), where h is the height of the treeclass Solution {public:int maxDepth(TreeNode* root) {if(root == NULL)return 0;stack<pair<TreeNode*, int>> s;s.push(make_pair(root, 1));int res = 0;while(!s.empty()){TreeNode* curNode = s.top().first;int depth = s.top().second;s.pop();if(curNode->left == NULL && curNode->right == NULL)res = max(res, depth);else{if(curNode->left)s.push(make_pair(curNode->left, depth + 1));if(curNode->right)s.push(make_pair(curNode->right, depth + 1));}}return res;}};int main() {return 0;}