222.完全二叉树的节点个数[https://leetcode.cn/problems/count-complete-tree-nodes/submissions/498293461/]
思路:递归法
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 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 countNodes(TreeNode root) {
int x = 0;
if (root == null) {
return 0;
}
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
while (!que.isEmpty()) {
List<Integer> list = new ArrayList<>();
int loop = que.size();
for (int i = 0; i < loop; i++) {
TreeNode temp = que.poll();
if (temp.left != null) {
que.offer(temp.left);
}
if (temp.right != null) {
que.offer(temp.right);
}
x++;
}
}
return x;
}
}
**-----------------------分割线-------------------------**
104.二叉树的最大深度[https://leetcode.cn/problems/maximum-depth-of-binary-tree/submissions/498058606/]
思路:递归法。迭代法在第十三天的博客中。
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
**-----------------------分割线-------------------------**
111.二叉树的最小深度[https://leetcode.cn/problems/minimum-depth-of-binary-tree/]
思路:递归法。迭代法在第十三天的博客中。
class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if(root.left!=null && root.right!=null){
return Math.min(leftDepth, rightDepth) + 1;
}else if(root.left==null && root.right!=null){
return rightDepth + 1;
}else {
return leftDepth + 1;
}
}
}
标签:right,TreeNode,int,代码,随想录,第十四天,return,root,left
From: https://www.cnblogs.com/cssg/p/17987799