代码随想录day16
迭代(层序遍历)
class Solution {
public int maxDepth(TreeNode root) {
List<TreeNode> pre = new ArrayList<>();
pre.add(root);
if(root == null){
return 0;
}
int num = 0;
while(!pre.isEmpty()){
List<TreeNode> tmp = pre;
pre = new ArrayList<>();
for(int i=0 ; i<tmp.size() ; i++){
TreeNode node = tmp.get(i);
if(node.left != null){
pre.add(node.left);
}
if(node.right != null){
pre.add(node.right);
}
}
num++;
}
return num;
}
}
递归
class Solution {
int num = 0;
public int maxDepth(TreeNode root) {
ans(root,0);
return num;
}
void ans(TreeNode tr , int tmp){
if(tr == null){
return;
}
tmp++;
num = Math.max(num,tmp);
ans(tr.left,tmp);
ans(tr.right,tmp);
tmp--;
}
}
迭代
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;
}
}
递归
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int maxChildDepth = 0;
for (Node child : root.children) {
int childDepth = maxDepth(child);
maxChildDepth = Math.max(maxChildDepth, childDepth);
}
return maxChildDepth + 1;
}
}
迭代
class Solution {
public int minDepth(TreeNode root) {
List<TreeNode> pre = new ArrayList<>();
pre.add(root);
if(root == null){
return 0;
}
int num = 0;
while(!pre.isEmpty()){
num++;
List<TreeNode> tmp = pre;
pre = new ArrayList<>();
for(int i=0 ; i<tmp.size() ; i++){
TreeNode node = tmp.get(i);
if(node.left == null && node.right == null){
return num;
}
if(node.left != null){
pre.add(node.left);
}
if(node.right != null){
pre.add(node.right);
}
}
}
return num;
}
}
递归
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;
}
}
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int result = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size -- > 0) {
TreeNode cur = queue.poll();
result++;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return result;
}
}