题目:
思路:
- 采用递归的主要思想。
- 确定递归终止条件,即结点为null。
- 模拟递归过程,即获得左右子树的最大深度,求出最大值加1,即为整个树的最大深度。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int MaxDepth(TreeNode root) {
if(root==null)
{return 0;}
else
{
int leftDepth=MaxDepth(root.left);
int rightDepth=MaxDepth(root.right);
return Math.Max(leftDepth,rightDepth)+1;
}
}
}