Skip to content

Commit a4fd08b

Browse files
author
Guanchen Zhao
committed
KthLargestElementInABST
1 parent 5ba9b1e commit a4fd08b

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package leetcode.solution.tree.bst;
2+
3+
import leetcode.structure.TreeNode;
4+
5+
import java.util.Stack;
6+
7+
/**
8+
* Kth Largest Element in a BST
9+
*/
10+
public class KthLargestElementInABST {
11+
12+
public static void main(String[] args) {
13+
Integer[] inorder = {3, 1, 10, null, 2, 7, null};
14+
TreeNode treeNode = TreeNode.constructTree(inorder);
15+
int k = 4;
16+
KthLargestElementRecursion recursion = new KthLargestElementRecursion();
17+
int ans = recursion.kthLargest(treeNode, k);
18+
System.out.println(ans);
19+
20+
21+
KthLargestElementIteration iteration = new KthLargestElementIteration();
22+
ans = iteration.kthLargest(treeNode, k);
23+
System.out.println(ans);
24+
25+
26+
inorder = new Integer[]{5, 3, 10, null, null, 7, 15, null, null, 14, 16};
27+
treeNode = TreeNode.constructTree(inorder);
28+
k = 6;
29+
ans = recursion.kthLargest(treeNode, k);
30+
System.out.println(ans);
31+
32+
33+
ans = iteration.kthLargest(treeNode, k);
34+
System.out.println(ans);
35+
}
36+
37+
38+
}
39+
40+
class KthLargestElementRecursion {
41+
/**
42+
* global variable, same as k
43+
* 全局变量,记录要找的排名
44+
*/
45+
private int kth;
46+
47+
/**
48+
* the order of current node
49+
* 当前节点的排名
50+
*/
51+
private int current;
52+
53+
/**
54+
* the value of final result
55+
* 结果值
56+
*/
57+
private int value;
58+
59+
60+
public int kthLargest(TreeNode root, int k) {
61+
kth = k;
62+
current = 0;
63+
helper(root);
64+
return value;
65+
}
66+
67+
/**
68+
* Inorder Traversal
69+
* 中序遍历
70+
* <p>
71+
* means sort from smallest to largest in the Binary Search Tree
72+
* 中序遍历即为二叉搜索树的从小到大排序
73+
*
74+
* @param root
75+
*/
76+
private void helper(TreeNode root) {
77+
if (root == null) {
78+
return;
79+
}
80+
81+
helper(root.right);
82+
83+
current++;
84+
85+
if (current == kth) {
86+
value = root.val;
87+
return;
88+
}
89+
90+
helper(root.left);
91+
}
92+
93+
94+
}
95+
96+
97+
class KthLargestElementIteration {
98+
public int kthLargest(TreeNode root, int k) {
99+
Stack<TreeNode> stack = new Stack<>();
100+
TreeNode p = root;
101+
int count = 0;
102+
103+
while (!stack.isEmpty() || p != null) {
104+
if (p != null) {
105+
stack.push(p); // Just like recursion
106+
p = p.right;
107+
108+
} else {
109+
TreeNode node = stack.pop();
110+
if (++count == k) {
111+
return node.val;
112+
}
113+
p = node.left;
114+
}
115+
}
116+
117+
return Integer.MIN_VALUE;
118+
}
119+
}

0 commit comments

Comments
 (0)