230-Kth-Smallest-Element in-a-BST
Previous105-Construct-Binary-Tree-from-Preorder-and-Inorder-TraversalNext106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal
Last updated
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
if(root==null){
return 0;
}
return calc(root,k);
}
//计算当前子树的根节点
private int countNodes(TreeNode root){
if(root==null){
return 0;
}
return 1+countNodes(root.left)+countNodes(root.right);
}
private int calc(TreeNode root,int k){
int leftCount=countNodes(root.left);
if(leftCount+1==k){
return root.val;
}else if(leftCount<k-1){
return calc(root.right,k-leftCount-1);
}else{
return calc(root.left,k);
}
}
}