Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Week_03/id_9/LeetCode_104_9.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.github.lifelab.leetcode.problemset;

/**
* 二叉树的最大深度 @https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
*
* @author Weichao Li (liweichao0102@gmail.com)
* @since 2019-06-09
*/
public class Solution104 {

public int maxDepth(TreeNode root) {
return depth(root, 0);
}

private int depth(TreeNode node, int depth) {

if (node == null) {
return 0;
}

depth++;

if (node.left == null && node.right == null) {
return depth;
}

int l = 0, r = 0;

if (node.left != null) {
l = depth(node.left, depth);
}

if (node.right != null) {
r = depth(node.right, depth);
}

return Math.max(l, r);
}
}
40 changes: 40 additions & 0 deletions Week_03/id_9/LeetCode_111_9.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.github.lifelab.leetcode.problemset;

import java.util.Objects;

/**
* 二叉树的最小深度 @see https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/submissions/
*
* @author Weichao Li (liweichao0102@gmail.com)
* @since 2019-07-07
*/
public class Solution111 {

public int minDepth(TreeNode root) {
return minDepth(root, 0);
}

public int minDepth(TreeNode node, int currentDepth) {

if (node == null) {
return currentDepth;
}

currentDepth++;

if (Objects.isNull(node.left) && Objects.isNull(node.right)) {
return currentDepth;
} else {

int minDepth = Integer.MAX_VALUE;
if (node.left != null) {
minDepth = Math.min(minDepth(node.left, currentDepth), minDepth);
}
if (node.right != null) {
minDepth = Math.min(minDepth(node.right, currentDepth), minDepth);
}
return minDepth;
}

}
}
50 changes: 50 additions & 0 deletions Week_03/id_9/LeetCode_547_9.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.github.lifelab.leetcode.problemset;

/**
* 朋友圈 @https://leetcode-cn.com/problems/friend-circles/
*
* @author Weichao Li (liweichao0102@gmail.com)
* @since 2019-07-07
*/
public class Solution547 {


public int findCircleNum(int[][] M) {
//二维数组长度,即所有人的个数
int length = M.length;
//统计朋友圈个数
int count = 0;
//访问标志
boolean[] flag = new boolean[length];
//对于每个人
for (int i = 0; i < length; i++) {
//如果未被访问
if (!flag[i]) {
//深度优先搜索,访问
dfs(i, M, flag);
//朋友圈个数+1
count++;
}
}
return count;
}

/**
* 深度优先搜索
*
* @param i 人的位置
* @param M 朋友圈
* @param flag 访问标识
*/
public void dfs(int i, int[][] M, boolean[] flag) {
//当前位占位
flag[i] = true;

for (int j = 0; j < M[i].length; j++) {

if (!flag[j] && M[i][j] == 1) {
dfs(j, M, flag);
}
}
}
}