题目描述node
给定一个二叉树,找出其最大深度。网络
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。spa
说明: 叶子节点是指没有子节点的节点。code
示例blog
给定二叉树 [3,9,20,null,null,15,7]
递归
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。leetcode
题目要求get
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 int maxDepth(struct TreeNode* root){ 11 12 }
题解it
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 int _max(int a,int b){ 11 return a>b?a:b; 12 } 13 14 int maxDepth(struct TreeNode* root){ 15 if(root==NULL)return 0; 16 /* 17 加这三行会快一些,在数据量小的时候(上限高) 18 if(root->left==NULL&&root->right==NULL)return 1; 19 else if(root->left==NULL)return maxDepth(root->right)+1; 20 else if(root->right==NULL)return maxDepth(root->left)+1; 21 */ 22 return 1+_max(maxDepth(root->left),maxDepth(root->right)); 23 }
签到递归题,递归题只要状况考虑周到了,尤为是根节点为空的状况,就应该不会写错。io
题目来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。