[LeetCode 题解]: Maximum Depth of Binary Tree

时间:2024-09-11 18:03:20

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.

题解: 题意比较清楚, 找到从root出发最长的一条路径的长度。 采用DFS即可。

相似的一道题: Minimux Depth of Binary Tree 解法: http://www.cnblogs.com/double-win/p/3737237.html

 /**
* 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 minDepth(TreeNode *root) {
if(root==NULL) return ;
if(root->left==NULL && root->right==NULL) return ; int Leftdepth = minDepth(root->left);
int Rightdepth = minDepth(root->right); if(Leftdepth==)
return Rightdepth+;
else if(Rightdepth==)
return Leftdepth+; return min(Leftdepth,Rightdepth)+;
}
};