标签:
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;同样如果根结点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1。如果既有右子树又有左子树呢?那该树的深度就是其左、右子树深度的较大值再加1。
按照上面的思路用递归的方法很容易实现,下面贴上代码:
/**
* 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) {
if(root==NULL){
return 0;
}
int left=maxDepth(root->left);
int right=maxDepth(root->right);
return (left>right?left:right)+1;
}
};
[LeetCode]Maximum Depth of Binary Tree
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/43797979