
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.
树的深度是从根节点开始(其深度为1)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。
class Solution {
private:
int depth = 0;
void maxDepthUtil(TreeNode *root , int d)
{
if(root == NULL)
return;
if(d > depth)
depth = d;
maxDepthUtil( root->left, d+1);
maxDepthUtil( root->right, d+1);
}
public:
int maxDepth(TreeNode *root) {
maxDepthUtil( root,1 );
return depth;
}
};//另一种写法
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == NULL)
return 0;
return max( maxDepth(root->left),maxDepth(root->right) )+1;
}
};leetcode_104_Maximum Depth of Binary Tree
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43865255