104. Maximum Depth of Binary Tree(C语言)
求二叉树最大深度
题目
Given the root of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100
解答
选用递归的方法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int Tra(struct TreeNode* root)
{
if(root == NULL)
return 0;
int left_max = Tra(root->left);
int right_max = Tra(root->right);
return (left_max >= right_max) ? left_max+1 : right_max+1;
}
int maxDepth(struct TreeNode* root){
int ret;
if(root == NULL) ret = 0;
else ret = Tra(root);
return ret;
}
总结
看到这个题时,想到两个思路:
(1)遍历二叉树,用一个int变量存储最大深度,不断迭代;
(2)用递归的方式,把一棵大树一层层看作一个个小树,相当于求每个小树的最大深度,一个树的深度 = max(左子树深度,右子树深度)+1。