您的位置:首页 > 其它

Leetcode 230. Kth Smallest Element in a BST

2017-01-27 04:33 369 查看
O(n).

public class Solution {
public int kthSmallest(TreeNode root, int k) {
// save the inorder of the tree
// from left to right, return kth element in the list
List<Integer> ret = new ArrayList<>();
inorder(root, ret);
return ret.get(k-1);
}

public static void inorder(TreeNode root, List<Integer> ret) {
if (root == null) return;
inorder(root.left, ret);
ret.add(root.val);
inorder(root.right, ret);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: