Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
注:题库和图片转自 www.leetcode.com ,所有权归www.leetcode.com仅供交流学习使用,不得用于商业用途
-----------------------------------------------------------------------------------------------------
我的解法:/**
* 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 maxDepth(TreeNode* root) {
int currentDepth = 0;
maxDep = 0;
if(root != NULL)
{
travelBinaryTree(root, currentDepth);
}
return maxDep;
}
private:
int maxDep;
void travelBinaryTree(TreeNode* node, int depth)
{
depth++;
maxDep = (depth > maxDep) ? depth : maxDep;
if(node->left)
travelBinaryTree(node->left, depth);
if(node->right)
travelBinaryTree(node->right, depth);
}
};
虽然结果正确,看了一下bbs上的讨论,感觉算法虽然不复杂但是太多代码冗余,leetcode上比较精简的一种解法
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root)
return 0;
return 1 + max(maxDepth(root->right), maxDepth(root->left));
}
};
利用return的时候累加+1和max宏取最大值来获得最精简的代码。