- Since the left node of the current node is always the smaller one, and the right node of the current node is always the bigger one, the algorithm is to keep going down the left while keeping count of how many time we go down the left.
- Every time we go to a left node, we check if count == k. If yes, we found our kth smallest element in the BST. If not, we keep going down the left nodes and if there is no more left nodes to go to, we then try the right nodes.
- Eventually our count will equal the k and that node's value is the answer (this is the iterative solution).
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import java.util.*; public class HelloWorld{ static class TreeNode { private TreeNode left; private TreeNode right; private TreeNode parent; int val; public TreeNode (TreeNode left, TreeNode right, int item) { this.left = left; this.right = right; this.val = item; } } int count = 0; int result = Integer.MIN_VALUE; public static void main(String []args){ TreeNode node3 = new TreeNode(null, null, 5); TreeNode node2 = new TreeNode(null, null, 19); TreeNode node1 = new TreeNode(node3, node2, 10); System.out.println(kthSmallest(node1, 1)); } public static int kthSmallest(TreeNode root, int k) { Stack<TreeNode> aStack = new Stack<TreeNode>(); TreeNode p = root; int count = 0; while(!aStack.isEmpty() || p != null) { if (p != null) { aStack.push(p); p = p.left; } else { TreeNode node = aStack.pop(); count++; if (count == k) { return node.val; } else { p = node.right; } } } return Integer.MIN_VALUE; } } |
No comments:
Post a Comment