您的位置:首页 > 其它

*LeetCode-Kth Smallest Element in a BST

2015-09-27 07:53 459 查看
一个函数来数这个root下一共多少node 非常简单 recursive

然后就是主函数中判断left有多少node的时候需要数右边 想清楚 +1 -1的事情 因为要算上root本身

public class Solution {
public int kthSmallest(TreeNode root, int k) {
if ( countNode ( root.left ) < k - 1)
return kthSmallest( root.right, k - 1 - countNode( root.left) );
else if ( countNode ( root.left ) >= k)
return kthSmallest( root.left, k);
else
return root.val;
}
public int countNode ( TreeNode node ){
if ( node == null )
return 0;
return 1 + countNode ( node.left ) + countNode ( node.right );
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: