给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree
注意:全局变量要清空,不然会影响LeetCode的测试结果,详细可看下面链接
为什么 LeetCode(力扣)「执行代码」正确,提交代码出错?
代码
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * struct TreeNode *left;
- * struct TreeNode *right;
- * };
- */
- int max=0;
- void order(struct TreeNode * root,int len)
- {
- if(root == NULL)
- {
- return ;
- }
- len++;
- if(len>max)
- max=len;
- order(root->left,len);
- order(root->right,len);
- }
- int maxDepth(struct TreeNode* root){
- int len=0;
- order(root,len);
- return max;
- }
结果:
