LeetCode Maximum Depth of Binary Tree
2016-02-23 18:04
316 查看
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.
思路分析:这题比較简单。关于树的题目通常都能够用递归解决,这题也不例外。递归解法的思路是返回左右子树中深度较大的子树深度加1作为自己的深度。每递归调用一次深度加1.
递归解法(DFS递归搜索)
非递归的解法须要借助队列实现,BFS搜索树节点,首先root入队列。然后不断从队列头取出节点,将该节点的左右孩子(假设有)入队列。直到队列为空。注意维护当前层次的节点数和下一层次的节点数。这样在每次换层的时候,把层次计数器level加1,最后返回level层次数作为结果就可以。因为每一个node訪问一次。时间复杂度O(n)。
非递归解法(借助队列BFS)
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路分析:这题比較简单。关于树的题目通常都能够用递归解决,这题也不例外。递归解法的思路是返回左右子树中深度较大的子树深度加1作为自己的深度。每递归调用一次深度加1.
递归解法(DFS递归搜索)
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0; return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } }
非递归的解法须要借助队列实现,BFS搜索树节点,首先root入队列。然后不断从队列头取出节点,将该节点的左右孩子(假设有)入队列。直到队列为空。注意维护当前层次的节点数和下一层次的节点数。这样在每次换层的时候,把层次计数器level加1,最后返回level层次数作为结果就可以。因为每一个node訪问一次。时间复杂度O(n)。
非递归解法(借助队列BFS)
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0; LinkedList<TreeNode> treeNodeQueue = new LinkedList<TreeNode>(); int level = 0; treeNodeQueue.add(root); int curLevelNum = 1;//# of nodes in the current level int nextLevelNum = 0;//# of nodes in the next level while(!treeNodeQueue.isEmpty()){ TreeNode curNode = treeNodeQueue.poll();//find and remove; different from peek curLevelNum--; if(curNode.left != null){ treeNodeQueue.add(curNode.left); nextLevelNum++; } if(curNode.right != null){ treeNodeQueue.add(curNode.right); nextLevelNum++; } if(curLevelNum == 0){ level++; curLevelNum = nextLevelNum; nextLevelNum = 0;//added a level } } return level; } }
相关文章推荐
- 个人工作记录---工作中遇到的sql查询语句解析
- iOS开发-CALayer
- pooler [转]
- js解析格式化json日期
- Jquery的事件绑定live方法在ios版的微信网站无法正常工作
- java 嵌套遍历文件夹里面的文件和文件夹
- SpringMVC传值
- iOS-OC常用传值方法
- 【SPOJ-LCM】The Time of Day【计数DP】【离散化】
- 创建安卓应用的 30 个经验教训
- Unity教程之-制作闪亮的星星Star(五):源码
- 流媒体传输协议综述(RTP-RTCP RTSP RTMP HTTP)
- solr4.9.0部署到tomcat7
- 第11章 Android的线程和线程池
- redis 学习笔记之环境搭建
- 在jsp中用JSP和JSTL获取服务器参数
- UIView的layoutSubviews和drawRect方法何时调用
- onSaveInstanceState和onRestoreInstanceState触发的时机
- 管理域控制器需要注意的问题
- Android Audio system Overview