二叉树的最大深度
题目描述:
思路:
这里采用的是迭代的方法,首先判断根节点是否为空,是则返回0,否则分别将左节点和右节点作为根节点进行遍历,每次+1,最后将左右子树得到的大者+1作为返回值.
注意:最大值+1是因为max记录的是层数(从0开始)
代码:
/**
* 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 ll=MaxDepth(root.left);
int rr=MaxDepth(root.right);
int max=ll>rr?ll:rr;
return max+1;
}
}
}