Skip to content

Commit 836a315

Browse files
committed
fd
1 parent 564ca68 commit 836a315

File tree

2 files changed

+15
-45
lines changed

2 files changed

+15
-45
lines changed

leetcode/solution/src/KthSmallestElementInBST.java

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -14,30 +14,6 @@
1414
public class KthSmallestElementInBST {
1515

1616
public int kthSmallest(TreeNode root, int k) {
17-
int[] kth = new int[1];
18-
inorderTraversal(root, k, kth);
19-
return kth[0];
20-
}
21-
22-
private int inorderTraversal(TreeNode root, int k, int[] kth) {
23-
if (root == null) {
24-
return k;
25-
}
26-
27-
k = inorderTraversal(root.left, k, kth);
28-
29-
if (--k == 0) {
30-
kth[0] = root.val;
31-
return 0;
32-
}
33-
34-
return inorderTraversal(root.right, k, kth);
35-
}
36-
37-
/**
38-
* 非递归法
39-
*/
40-
public int kthSmallest2(TreeNode root, int k) {
4117
Stack<TreeNode> stack = new Stack<>();
4218
while (root != null || !stack.isEmpty()) {
4319
if (root != null) {
@@ -59,7 +35,7 @@ public int kthSmallest2(TreeNode root, int k) {
5935
/**
6036
* Morris
6137
*/
62-
private int kthSmallest3(TreeNode root, int k) {
38+
private int kthSmallest2(TreeNode root, int k) {
6339
TreeNode temp;
6440

6541
while (root != null) {

leetcode/src/Main.java

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,23 @@
44

55
public class Main {
66

7-
public static int diameterOfBinaryTree(TreeNode root) {
8-
if (root == null) {
9-
return 0;
7+
public int kthSmallest(TreeNode root, int k) {
8+
Stack<TreeNode> stack = new Stack<>();
9+
while (!stack.isEmpty() || root != null) {
10+
if (root != null) {
11+
stack.push(root);
12+
root = root.left;
13+
} else {
14+
root = stack.pop();
15+
if (--k == 0) {
16+
return root.val;
17+
}
18+
root = root.right;
19+
}
1020
}
11-
return dfs(root, false);
12-
}
13-
14-
public static int dfs(TreeNode root, boolean flag) {
15-
if (root == null) {
16-
return -1;
17-
}
18-
return flag ? Math.max(dfs(root.left, true) + 1, dfs(root.right, true) + 1) :
19-
Math.max(Math.max(dfs(root.left, false), dfs(root.right, false)),
20-
dfs(root.left, true) + 2 + dfs(root.right, true));
21+
return 0;
2122
}
2223

2324
public static void main(String[] args) {
24-
TreeNode node4 = new TreeNode(4);
25-
TreeNode node5 = new TreeNode(5);
26-
TreeNode node2 = new TreeNode(2, node4, node5);
27-
TreeNode node3 = new TreeNode(3);
28-
TreeNode node1 = new TreeNode(1, node2, node3);
29-
int len = diameterOfBinaryTree(node1);
30-
System.out.println(String.format("len = %d", len));
3125
}
3226
}

0 commit comments

Comments
 (0)