[LeetCode]Kth Smallest Element in a BST

public class Solution {
    TreeNode result = new TreeNode(0);
    public int kthSmallest(TreeNode root, int k) {
        helper(root, k);
        return result.val;
    }
    public int helper(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        int left = helper(root.left, k);
        if (left == k - 1) {
            result = root;
        }
        int right = helper(root.right, k - left - 1);
        return left + right + 1;
    }
}

 

posted @ 2015-11-27 16:33  Weizheng_Love_Coding  阅读(89)  评论(0编辑  收藏  举报