二叉树最大深度
//1.迭代法
public int maxdepth(Leetcode.TreeNode root){
int depth = 0;
if (root == null){
return 0;
}
Deque<Leetcode.TreeNode> deque = new LinkedList<>();
deque.offer(root);
while(!deque.isEmpty()){
int size = deque.size();
depth++;
//遍历辅助队列
for (int i = 0;i<size;i++){
Leetcode.TreeNode node = deque.poll();
//将此节点的左右节点压入队列中
if (node.left != null)deque.offer(node.left);
if (node.right != null)deque.offer(node.right);
}
}
return depth;
}
//递归版
public static int maxdepth2(TreeNode root) {
if (root == null) {
return 0;
}
int leftdepth = maxdepth2(root.left);
int rightdepth = maxdepth2(root.right);
return Math.max(leftdepth, rightdepth) + 1;
}
思路:利用队列进行层序遍历,然后利用队列做辅助结构,对深度进行+1.
|