Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 22, 2017 21:47
Show Gist options
  • Select an option

  • Save cixuuz/fed292dbf3384825b73b9bdc2698a28d to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/fed292dbf3384825b73b9bdc2698a28d to your computer and use it in GitHub Desktop.
[230. Kth Smallest Element in a BST] #leetcode
class Solution {
private Integer result;
private Integer count = 0;
public int kthSmallest(TreeNode root, int k) {
dfs(root, k);
return result;
}
public void dfs(TreeNode node, int k) {
if (count > k || node == null) return;
dfs(node.left, k);
// do sth
count++;
if (k == count) result = node.val;
dfs(node.right, k);
}
}
class Solution1 {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
int count = 0;
while (!stack.isEmpty() || p != null) {
if (p != null) {
stack.push(p);
p = p.left;
} else {
TreeNode node = stack.pop();
count++;
if (count == k) return node.val;
p = node.right;
}
}
return Integer.MIN_VALUE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment