需要注意区别二叉树的深度和高度的区别,深度是指树从根结点到叶子节点走过的结点数,而高度是指树节点到叶子节点走过的结点数。深度是从上到下数的,而高度是从下往上数。 这题如果用递归法的话就很好做,可以递归求出这棵二叉树左子树最大深度和右子树最大深度,然后比较两边取最大值就是这个二叉树的最大深度了。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int right = maxDepth(root.right);
int left = maxDepth(root.left);
return Math.max(right, left) + 1;
}
}
559. N 叉树的最大深度 这题如果用递归法解题和题104是相同的,解法如下:
//递归解法
class Solution {
public int maxDepth(Node root) {
if(root == null){
return 0;
}
int depth = 0;
if(root.children != null){
for(Node children : root.children){
depth = Math.max(depth, maxDepth(children));
}
}
return depth + 1;
}
}
不难得知如果用层序遍历其实同样可以求出二叉树的最大深度,因为遍历了多少层,这个层数就是树深。所以还有一种迭代解法:
//迭代法题解
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
int depth = 0;
Queue<Node> que = new LinkedList<>();
que.offer(root);
while(!que.isEmpty()){
depth ++;
int len = que.size();
while(len > 0){
Node node = que.poll();
for(int i = 0; i < node.children.size(); i ++){
if(node.children.get(i) != null){
que.offer(node.children.get(i));
}
}
len --;
}
}
return depth;
}
}
111. 二叉树的最小深度 这题乍一看和104题一模一样只需要把比较最大值换成最小值就行了,但其实这样写的话ac不会通过,因为这个思路忽略了左子树或右子树全为空的情况,所以比较最小值之前需要给左右子树判空,那么这题的递归解法就出来了。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if(root.left == null){
return right + 1;
}
if(root.right == null){
return left + 1;
}
return Math.min(left, right) + 1;
}
}
222. 完全二叉树的节点个数建议先补充了解完全二叉树的定义,然后递归法秒了。
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
//int res = 0;
int rightRes = countNodes(root.right);
int leftRes = countNodes(root.left);
return rightRes + leftRes + 1;
}
}