层序遍历的应用:
移步->LeetCode 104. 二叉树的最大深度
移步->LeetCode 102. 二叉树的层序遍历
移步->LeetCode 226. 翻转二叉树
移步-LeetCode 515. 在每个树行中找最大值
层序遍历&&后序遍历&&2先序遍历
标准的层序遍历,每次遍历完一层记录深度即可
class Solution {
public int maxDepth(TreeNode root) {
Queue<TreeNode> que = new LinkedList<TreeNode>();
int depth = 0;
if(root == null) return depth;
que.offer(root);
while(!que.isEmpty()){
int len = que.size();
while(len>0){
TreeNode curNode = que.poll();
if(curNode.left!=null) que.offer(curNode.left);
if(curNode.right!=null) que.offer(curNode.right);
len--;
}
depth++;
}
return depth;
}
}
后序遍历
这里要搞清楚为什么可以使用后序遍历,因为这里要求的根结点的最大深度,就是树的高度。所以可以使用后序遍历,遍历到根结点。代码很简洁。
class solution {
/**
* 递归法
*/
public int maxdepth(treenode root) {
if (root == null) {
return 0;
}
int leftdepth = maxdepth(root.left);
int rightdepth = maxdepth(root.right);
return math.max(leftdepth, rightdepth) + 1;
}
}
前序遍历
使用前序遍历实现真正的求最大深度。(为什么说是真正的呢?因为深度就是由根到叶子节点计算的,所以前序遍历是最合适的)。这种做法默认root的深度为1,并且每个节点都有一个深度。每次递归都更新一次最大深度。
class Solution {
public int result = 0;
public int maxDepth(TreeNode root) {
if(root == null) return result;
getdepth(root,1);
return result;
}
void getdepth(TreeNode root,int depth){
result = depth > result?depth:result;
if(root.left == null && root.right == null) return; //结束当前结点的递归
if(root.left!=null){
depth++;
getdepth(root.left,depth);
depth--;
}
if(root.right!=null){
depth++;
getdepth(root.right,depth);
depth--;
}
}
}
回溯过程图
为了理解这里return的用法和整个遍历过程,我们画图看看。
完美!