二叉树的的最大深度遍历非递归版
描述:给定一个二叉树,返回二叉树的最大深度
思路:利用队列的先进先出思想对二叉树进行层级遍历,每遍历完一层,就将深度+1
具体实现:
1、首先判断二叉树是否为空,如果为空,直接 return 0
2、如果不为空,首先将根节点入队,然后对队列进行遍历
3、初始化三个变量 depth 深度,count 计数器,nextCount 层级节点数,这里就是利用count和nextCount的之间进行判断,来进行判断每层是否遍历完, 4、当队列不为空的时候,循环出队列,count 开始计数,因为二叉树不为空的情况下,则必有根节点,所以第3步nextCount = 1,然后将 firstNode的左右子节点入队,此时 count = nextCount,则深度 +1,此时 队列的 size 即为下一层级的节点数目,初始化 nextCount = queue.size()
5、重复步骤四,直至队列为空,表明二叉树已经全部遍历完毕,此时depth则为二叉树的最大深度
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int depth = 0,count = 0,nextCount = 1;
while(queue.size() != 0){
TreeNode firstNode = queue.poll();
count++;
if(firstNode.left != null){
queue.add(firstNode.left);
}
if(firstNode.right != null){
queue.add(firstNode.right);
}
if(count == nextCount){
nextCount = queue.size();
count = 0;
depth++;
}
}
return depth;
}
}
递归版:递归版思路比较简单就不再详述
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left > right ? left + 1: right + 1;
}
}