Monday, November 2, 2015

[Leetcode]Kth Smallest Element in a BST

 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
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode travel = root;
        while (root != null){
            stack.push(root);
            root = root.left;
        }
        int total = 0;
        while (!stack.isEmpty()){
            total++;
            TreeNode temp = stack.pop();
            if (total == k){
                return temp.val;
            }
            if (temp.right != null){
                temp = temp.right;
                while (temp!=null){
                    stack.push(temp);
                    temp = temp.left;
                }
            }
        }
        return -1;
    }
}

No comments:

Post a Comment