Last active
August 22, 2017 21:47
-
-
Save cixuuz/fed292dbf3384825b73b9bdc2698a28d to your computer and use it in GitHub Desktop.
[230. Kth Smallest Element in a BST] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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