二叉树的最大深度
题目链接
思路:刚刚学习了二叉树的层序遍历发现本题求的二叉树的深度其实也就是二叉树的层数
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int depth=0;
Queue<TreeNode> queue = new LinkedList<>();//利用队列遍历二叉树的每一层
queue.add(root);
while(!queue.isEmpty()){
int size=queue.size();
depth++;
while(size>0){
TreeNode temp=queue.peek();
queue.poll();
if(temp.left!=null){
queue.add(temp.left);
}
if(temp.right!=null){
queue.add(temp.right);
}
size--;
}
}
return depth;
}
}
递归法:
递归三部曲
1.确定递归函数的参数和返回值:参数是传入的根节点,返回值为二叉树的深度,类型为int
2.确定终止条件:当root为空节点时退出
3.确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getDepth(TreeNode node){
if(node==null){
return 0;
}
int leftDepth=getDepth(node.left);
int rightDepth=getDepth(node.right);
return Math.max(leftDepth,rightDepth)+1;
}
public int maxDepth(TreeNode root) {
int res=getDepth(root);
return res;
}
}
二叉树的最小深度
题目链接:
相比二叉树的最大深度,
在处理节点的过程中,最大深度很容易理解,最小深度就不那么好理解,如图:
这就重新审题了,题目中说的是:最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点。
什么是叶子节点,左右孩子都为空的节点才是叶子节点!
所以当左节点为空时,最小深度就为1+右子树的最小深度,当右节点为空时,最小深度就等于1+左子树的最小深度
都不为空时 最小深度等于min(左子树最小深度,右子树最小深度)+1
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getDepth(TreeNode node){
if(node==null){
return 0;
}
int leftDepth=getDepth(node.left);
int rightDepth=getDepth(node.right);
if(node.left==null){
return 1+rightDepth;
}
if(node.right==null){
return 1+leftDepth;
}
return Math.min(leftDepth,rightDepth)+1;
}
public int minDepth(TreeNode root) {
return getDepth(root);
}
}
完全二叉树的节点个数
题目链接;
222. 完全二叉树的节点个数 - 力扣(LeetCode)
类属于求最大深度,先将左右子树的节点个数求出,最后相加再加1即可
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getsum(TreeNode node){
if(node==null){
return 0;
}
int leftSum=getsum(node.left);
int rightSum=getsum(node.right);
return leftSum+rightSum+1;
}
public int countNodes(TreeNode root) {
return getsum(root);
}
}