Code Ganker: Maximum Depth of Binary Tree -- LeetCode

2014年2月5日星期三

Maximum Depth of Binary Tree -- LeetCode

原题链接:http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
这是一道比较简单的树的题目,可以有递归和非递归的解法,递归思路简单,返回左子树或者右子树中大的深度加1,作为自己的深度即可,代码如下:
public int maxDepth(TreeNode root) {
    if(root == null)
        return 0;
    return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
非递归解法一般采用层序遍历(相当于图的BFS),因为如果使用其他遍历方式也需要同样的复杂度O(n). 层序遍历理解上直观一些,维护到最后的level便是树的深度。代码如下:
public int maxDepth(TreeNode root) {
    if(root == null)
        return 0;
    int level = 0;
    LinkedList queue = new LinkedList();
    queue.add(root);
    int curNum = 1; //num of nodes left in current level
    int nextNum = 0; //num of nodes in next level
    while(!queue.isEmpty())
    {
        TreeNode n = queue.poll();
        curNum--;
        if(n.left!=null)
        {
            queue.add(n.left);
            nextNum++;
        }
        if(n.right!=null)
        {
            queue.add(n.right);
            nextNum++;
        }
        if(curNum == 0)
        {
            curNum = nextNum;
            nextNum = 0;
            level++;
        }
    }
    return level;
}
总体来说我觉得这道题可以考核树的数据结构,也可以看看对递归和非递归的理解。相关的扩展可以是Minimum Depth of Binary Tree.

8 条评论:

  1. 第一个的时间和空间复杂度是O(n)么?他会要求不能用递归?递归感觉好叼啊~

    回复删除
    回复
    1. 第一个的时间是O(n),空间是递归栈的大小,也就是树的高度。会的,面试里面经常会要求两种都写,都得掌握~

      删除
  2. TreeNode 可以直接用么?不要单独写个类?还有Queue好像有单独的api可以用?

    回复删除
    回复
    1. TreeNode 是 LeetCode里面默认的数据结构,面试的时候你也可以假设有这个数据结构,不过如果要你写肯定也要能写出来,其实很简单。 java里面的linkedlist,stack,queue都可以用LinkedList来实现,都有对应的接口push,pop,offer,poll等。

      删除
    2. nice! 居然可以回复了。。

      删除
  3. 请问一下,这个题目用DFS的非递归方式能实现吗?

    回复删除
    回复
    1. 可以的,任何递归程序都可以写成非递归形式,只是代码比较复杂而已哈~

      删除
    2. 好的明白了,我用BFS实现了下。另外想追问下,如果用BFS的话。空间复杂度应该是多少呢?
      我想的话应该是Queue的size,但是queue的size在变化,这时候应该怎么回答空间复杂度呢?
      我觉得回答O(n)似乎也可以,但是O(n)不是tight bound对吗?

      删除