Skip to content

Commit 322663e

Browse files
committed
binaryTree
1 parent 420ee4e commit 322663e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.algorithm.leetcode.binaryTree;
2+
3+
import com.algorithm.leetcode.tree.TreeNode;
4+
5+
import java.util.ArrayDeque;
6+
import java.util.Deque;
7+
8+
/**
9+
* @author tanglijuan
10+
* @date 2021/12/20
11+
* 二叉搜索树中第K小的元素
12+
* 给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
13+
*/
14+
public class KthSmallest {
15+
//方法一:可以通过中序遍历,放到数组中,然后取出 时间复杂度O(n)
16+
17+
//方法二:二叉搜索树的中序遍历是有序的,因此我们只需要对二叉搜索树执行中序遍历,并返回第 k 小的值即可。
18+
public int kthSmallest(TreeNode root, int k) {
19+
Deque<TreeNode> d = new ArrayDeque<TreeNode>();
20+
while (root != null || !d.isEmpty()) {
21+
while (root != null) {
22+
d.addLast(root);
23+
root = root.left;
24+
}
25+
root = d.pollLast();
26+
if (--k == 0) {
27+
return root.val;
28+
}
29+
root = root.right;
30+
}
31+
return -1;
32+
}
33+
}
34+

0 commit comments

Comments
 (0)