原题:
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.
这道题挺简单的,我的想法便是,对树进行递归计算高度。
如果是一棵有两个儿子的树,分别返回两个子树的高度,再加上自己已有的高度便是答案;
如果一个结点只有一个树,同样返回两个子树的高度,但为了防止出错,我们在前面会判断传递进来的节点是否为NULL,如果为NULL返回0;
如果是叶子节点,那么直接返回1
代码如下:
#include<iostream>
#include <algorithm>
/*definition for binary tree
* 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 count=1;
if (root==NULL) return 0;
if (root->right!=NULL || root->left!=NULL)
count = count + max(maxDepth(root->right),maxDepth(root->left));
else count = 1;
return count;
}
};