104. Maximum Depth of Binary Tree
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.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------题解:
本题是关于树和DFS的题目,要求一棵树的最大深度,相当于就是求树高。
我的思路是循环递归调用maxDepth函数。设置两个整型变量l和r分别存储当前节点的左子树和右子树的树高,每递归一次,l和r的数值就+1,直到该节点没有左子树或右子树时,此时达到递归基,即这棵树只有一个节点,树高为0。最后比较l和r的大小,取最大的为最终的结果。
代码:
/**
* 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 l, r;
if (root == NULL)
return 0;
else
{
l = maxDepth(root->left) + 1;
r = maxDepth(root->right) + 1;
}
if (l > r)
return l;
else
return r;
}
};