104. Maximum Depth of Binary Tree(以后做了树的宽度后需要补充)

本文探讨了二叉树的最大深度问题,提供了递归和非递归两种解决方案。递归方法利用深度优先搜索原理,非递归则采用广度优先遍历实现。

1、题目
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example:
Given binary tree [3,9,20,null,null,15,7],

   3
  /  \
9    20
      / \
   15   7
return its depth = 3.
2、分析与解答(递归和非递归)
这道题一开始我就直接想了二叉树的遍历(前中后序,没想到按层),而且还局限于非递归的遍历,直接没做出来。
后来发现使用递归的方法很简单,如果当前节点为NULL,那当前的深度为0;若不为空,则是左孩子的高度和右孩子高度的较大者加1。代码为:

public int maxDepth(TreeNode root) {
       if(root == null)
           return 0;
        int left = maxDepth(root.left) + 1;
        int right = maxDepth(root.right) + 1;
        return (left > right) ? left : right;
    }

3、非递归的算法
以层次遍历为基础,类似广度优先遍历,每遍历完一层,深度加一。代码如下:

 public int maxDepth(TreeNode root) {
        if(root == null)//注意边界条件
            return 0;
        int level = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode last = root;
        TreeNode nlast = null;
        TreeNode cur = root;
        queue.offer(root);
        while(!queue.isEmpty()){
            cur = queue.poll();         
            if(cur.left != null){
                queue.offer(cur.left);
                nlast = cur.left;
            }
            if(cur.right != null){
                queue.offer(cur.right);
                nlast = cur.right;
            }
            if(cur == last){
                last = nlast;
                level++;
            }
        }
        return level;
    }

不过这里有一个关键的问题:如何知道每一层节点的数量呢(或者这行结束了呢)?这里借鉴另一道题的思路—-二叉树的按层打印(需要换行)。

采用两个指针:last和nlast。last指向当前行的最后一个节点,nlast指向下一行的最后一个节点。当从队列中弹出一个节点和last相同,那么说明要换行了,此时深度加一,last指向nlast。

注意:last开始指向根节点,nlast开始指向null,之后只需要nlast跟踪记录队列中最新的节点。这是因为新加入队列的节点必定是目前所发现的下一行的最右节点。当出队的元素和last相同的时候,nlast一定是下一行的最右边的节点。

还有别的非递归的方法可以参考:http://blog.csdn.net/snow_7/article/details/51818580
这个使用了宽度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值