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.
Subscribe to see which companies asked this question
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
如果二叉树为空,则深度为0
如果不为空,分别求左子树的深度和右子树的深度,去最大的再加1,因为根节点深度是1,要加进去。
/**
* 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) {
if (NULL == root)
return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return l > r ? l + 1:r+1;
}
};
/**
* 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 height(TreeNode* root) {
if(root==NULL)
return 0;
else{
int l=height(root->left);
int r=height(root->right);
return 1+((l>r)?l:r);
}
}
int maxDepth(TreeNode* root) {
if (NULL == root)
return 0;
int l = height(root->left);
int r = height(root->right);
return l > r ? l + 1:r+1;
}
};