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.
方法一:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
int leftcount=0;
int rightcount=0;
if(root==null)
return 0;
else if(root.left==null && root.right==null)
return 1;
else if(root.left==null&&root.right!=null)
{
rightcount=1+ maxDepth(root.right);
}
else if(root.left!=null&&root.right==null)
{
leftcount=1+ maxDepth(root.left);
}
else
{
rightcount=1+maxDepth(root.right);
leftcount=1+maxDepth(root.left);
}
return leftcount>=rightcount?leftcount:rightcount;
}
}
方法二:
class Solution { 11 public: 12 int maxDepth(TreeNode *root) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if (root == NULL) 16 return 0; 17 18 int leftDepth = maxDepth(root->left); 19 int rightDepth = maxDepth(root->right); 20 21 return max(leftDepth, rightDepth) + 1; 22 } 23 };