标签:树、深度优先搜索
• 题号:104
• 难度:简单
• 题目:二叉树的最大深度
• https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
借鉴大神的一行代码解法,不过也可以用dfs
/**
* 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) {
return (root==NULL)? 0:max(maxDepth(root->left),maxDepth(root->right))+1;
}
};