Skip to content

Commit 1628338

Browse files
author
liwentian
committed
kth smallest elements in bst
1 parent 7f43cfa commit 1628338

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

‎doc/Leetcodes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
|221|[Maximal Square](https://leetcode.com/problems/maximal-square/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximalSquare.java)|80|
8585
|222|[Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountCompleteTreeNodes.java)|70|
8686
|226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/InvertBinaryTree.java)|80|
87+
|230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java)|85|
8788
|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromeLinkedList.java)|75|
8889
|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)|[Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinarySearchTree.java)|100|
8990
|236|[Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinaryTree.java)|85|
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.inuker.solution;
2+
3+
/**
4+
* Created by dingjikerbo on 16/11/30.
5+
*/
6+
7+
public class KthSmallestElementInBST {
8+
9+
public int kthSmallest(TreeNode root, int k) {
10+
int[] kth = new int[1];
11+
inorderTraversal(root, k, kth);
12+
return kth[0];
13+
}
14+
15+
private int inorderTraversal(TreeNode root, int k, int[] kth) {
16+
if (root == null) {
17+
return k;
18+
}
19+
20+
k = inorderTraversal(root.left, k, kth);
21+
22+
if (--k == 0) {
23+
kth[0] = root.val;
24+
return 0;
25+
}
26+
27+
return inorderTraversal(root.right, k, kth);
28+
}
29+
}

0 commit comments

Comments
 (0)