文章目录
二叉树的深度
题目
给定一个二叉树 root ,返回其最大深度。
二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。
思路
采用递归的思想,分别计算根节点左右子树深度,然后比较左右子树深度大小,最大的值+1即为所求结果;
代码实现
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
二叉树的层序遍历
题目
给你二叉树的根节点 root ,返回其节点值的层序遍历 (即逐层地,从左到右访问所有节点)。
Leetcode链接
思路
对于二叉树的层序遍历,需要利用队列的性质进行实现;
代码实现
public static List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return null;
}
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node == null) {
continue;
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
list.add(node.val);
}
result.add(list);
}
return result;
}