题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
思路
写一个函数,传入当前节点和当前深度,判断当前节点是否为空节点,若不为空节点则count加1,若为空节点则返回count。返回左右子树深度较大者。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class MaxDepth {
public int maxDepth(TreeNode root) {
int count = 0;
return depth(root, count);
}
private int depth(TreeNode t, int count)
{
if(t == null)
return count;
else
count++;
return Math.max(depth(t.left, count), depth(t.right, count));
}
}

878

被折叠的 条评论
为什么被折叠?



