代码随想录算法训练营
今日任务
104.二叉树的最大深度 ,559.n叉树的最大深度 ,111.二叉树的最小深度 ,222.完全二叉树的节点个数
104.二叉树的最大深度
/**
* 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) {
//递归,利用后序排序
return getDepth(root);
}
public int getDepth(TreeNode root){
if(root==null){
//叶子节点
//其实深度就是从叶子节点开始向上加的
return 0;
}
int leftDepth = getDepth(root.left);
//System.out.println(leftDepth);
int rightDepth = getDepth(root.right);
//System.out.println(rightDepth);
return 1+Math.max(leftDepth,rightDepth);
}
}
559.n叉树的最大深度
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
//迭代法
//利用队列
if(root==null){
return 0;
}
if(root.children==null){
return 1;
}
Queue<Node> queue=new LinkedList<>();
queue.offer(root);
int depth=0;
while (!queue.isEmpty()){
depth++;
int size=queue.size();
while(size>0){
size--;
Node top = queue.poll();
List<Node> children = top.children;
if(children==null){
continue;
}
for (Node child : children) {
queue.offer(child);
}
}
}
return depth;
}
}
111.二叉树的最小深度
/**
* 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 minDepth(TreeNode root) {
int result=0;
if(root==null){
return result;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
result++;
int flag=0;
while(!queue.isEmpty()){
int size=queue.size();
while(size>0){
size--;
TreeNode poll = queue.poll();
if(poll.left!=null){
queue.offer(poll.left);
}
if(poll.right!=null){
queue.offer(poll.right);
}
if(poll.right==null&&poll.left==null){
//叶子节点
flag=1;
break;
}
}
if(flag==0){
result++;
}else{
break;
}
}
return result;
}
}
222.完全二叉树的节点个数
/**
* 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) {
return getDepth(root);
}
public int getDepth(TreeNode node) {
if(node==null){
return 0;
}
int leftDepth=getDepth(node.left);
int rightDepth=getDepth(node.right);
//String str=node.val+" "+leftDepth+" "+rightDepth;
//System.out.println(str);
return leftDepth+rightDepth+1;
}
}