class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeDepth {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
// 返回左右子树深度的较大值加上当前节点的深度(1)
return Math.max(leftDepth, rightDepth) + 1;
}
}
public static void main(String[] args) {
// 创建一个二叉树示例
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
BinaryTreeDepth binaryTreeDepth = new BinaryTreeDepth();
int depth = binaryTreeDepth.maxDepth(root);
System.out.println("二叉树的深度为:" + depth);
}
}
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeDepth {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode current = queue.poll();
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
depth++;
}
return depth;
}
public static void main(String[] args) {
// 创建一个二叉树示例
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
BinaryTreeDepth binaryTreeDepth = new BinaryTreeDepth();
int depth = binaryTreeDepth.maxDepth(root);
System.out.println("二叉树的深度为:" + depth);
}
}
在该迭代的实现方式参考了 坚持刷题|二叉树的层序遍历,使用了队列来进行层序遍历,每遍历一层,深度加1。这样可以在不使用递归的情况下计算二叉树的深度。这种方法的时间复杂度同样是 O(N),其中 N 是二叉树中的节点数。