`

Kth Smallest Element in a BST

阅读更多
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

给定一个二叉搜索树,从中找到第k小的元素。根据二叉搜索树的性质中序遍历正好是二叉搜索树的升序排列,当我们遍历到第k个元素是返回就可以了。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int count = 0;
    int result = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root == null) return 0;
        dfs(root, k);
        return result;
    }
    public void dfs(TreeNode root, int k) {
        if(root == null) return;
        dfs(root.left, k);
        if(++count == k) {
            result = root.val;
            return;
        }
        dfs(root.right, k);
    }
}


我们还可以先计算出左子树的节点个数leftnum,左子树的元素都小于根节点的元素,我们用leftnum与k比较,如果k > leftnum, 则k不再左子树中,我们只需要在右子树中找到第k - leftnum个元素就可以了;如果k < leftnum, 我们继续在左子树中找第k个元素;如果相等,我们就返回左子树的根节点。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        if(root == null) return 0;
        int left = getNode(root.left);
        if(left + 1 == k) {
            return root.val;
        } else if(left + 1 < k) {
            return kthSmallest(root.right, k - left - 1);
        } else {
            return kthSmallest(root.left, k);
        }
    }
    public int getNode(TreeNode root) {
        if(root == null) return 0;
        return 1 + getNode(root.left) + getNode(root.right);
    }
}
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics