From 2dda42f5705aa3bd8c40e2f3f30e3377e72cfac1 Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Sun, 1 Sep 2024 02:20:54 +0800 Subject: [PATCH] 2024/8/31 LeetCode Hot100 binaryTree --- .../com/cool/hot100/binary_tree/Num199.java | 64 +++++++++++++++++++ .../com/cool/hot100/binary_tree/Num230.java | 35 ++++++++++ 2 files changed, 99 insertions(+) create mode 100644 src/main/java/com/cool/hot100/binary_tree/Num199.java create mode 100644 src/main/java/com/cool/hot100/binary_tree/Num230.java diff --git a/src/main/java/com/cool/hot100/binary_tree/Num199.java b/src/main/java/com/cool/hot100/binary_tree/Num199.java new file mode 100644 index 0000000..9a8b228 --- /dev/null +++ b/src/main/java/com/cool/hot100/binary_tree/Num199.java @@ -0,0 +1,64 @@ +package com.cool.hot100.binary_tree; + +import sun.reflect.generics.tree.Tree; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * Created with IntelliJ IDEA. + * + * @Author: Cool + * @Date: 2024/09/01/1:58 + * DayNumber 2 + * Hard 2 + * Level 4 + */ +public class Num199 { + + + public List rightSideView(TreeNode root) { +// List list = new ArrayList<>(); +// dfs(root, list, 0); +// return list; + return bfs(root); + } + + private List bfs(TreeNode root) { + List list = new ArrayList<>(); + if (root == null) return list; + Queue queue = new LinkedList<>(); + queue.add(root); + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + if (node != null && node.left != null) { + queue.add(node.left); + } + if (node != null && node.right != null) { + queue.add(node.right); + } + if (i == size - 1 && node != null) { + list.add(node.val); + } + } + } + return list; + } + + + //此为dfs解法 + private void dfs(TreeNode root, List list, int deep) { + if (root == null) return; + if (list.size() == deep) { + list.add(root.val); + } + dfs(root.right, list, ++deep); + dfs(root.left, list, deep); + } + + +} diff --git a/src/main/java/com/cool/hot100/binary_tree/Num230.java b/src/main/java/com/cool/hot100/binary_tree/Num230.java new file mode 100644 index 0000000..e7032f4 --- /dev/null +++ b/src/main/java/com/cool/hot100/binary_tree/Num230.java @@ -0,0 +1,35 @@ +package com.cool.hot100.binary_tree; + +/** + * Created with IntelliJ IDEA. + * + * @Author: Cool + * @Date: 2024/09/01/1:43 + * DayNumber 1 + * Hard 2 + * Level 3 + */ +public class Num230 { + + + public int kthSmallest(TreeNode root, int k) { + int[] arr = new int[k]; + dfs(root, arr, 0); + return arr[arr.length - 1]; + } + + private int dfs(TreeNode root, int[] arr, int num) { + if (root == null) { + return num; + } + if (num >= arr.length) return num; + num = dfs(root.left, arr, num); + if (num >= arr.length) return num; + arr[num++] = root.val; + if (num >= arr.length) return num; + num = dfs(root.right, arr, num); + + return num; + } + +}