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
这个使用了宽度。
本文探讨了二叉树的最大深度问题,提供了递归和非递归两种解决方案。递归方法利用深度优先搜索原理,非递归则采用广度优先遍历实现。
&spm=1001.2101.3001.5002&articleId=79405611&d=1&t=3&u=ea500559c4424a5890446a82afbc0edf)
467

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



