很容易。 做法也比较多。 可以直接递归本函数返回最大的子树高度+1;也可以利用队列遍历每个节点,队列保存节点和高度的键值对。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int MAX=0;
public int maxDepth(TreeNode root) {
fun( root,0 );
return MAX;
}
void fun( TreeNode root,int count)
{
if( root==null )
{
return;
}
count++;
if( count>MAX )
{
MAX=count;
}
fun(root.left,count);
fun(root.right,count);
}
}