*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 );
}
}
然后就是主函数中判断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 );
}
}
相关文章推荐
- 关于java语言递增和递减的理解
- vijos1774:机器翻译
- android第一个用户进程Init进程
- PHP优化之mysql结构
- Xcode出现may cause a leak的解决
- Xcode出现may cause a leak的解决
- Xcode出现may cause a leak的解决
- 常用DIV+CSS命名大全集合
- cocos2dx and c++ 的小坑
- svn check in ,check out, import, export
- java作业
- VC 使用combox
- 广搜——路径寻找
- 【C++ Primer】高级主题
- 【C++ Primer】面向对象编程与泛型编程
- 【C++ primer】类和数据抽象
- *LeetCode-Peeking Iterator
- 【C++ Primer】容器和算法
- vijos1775:乌龟棋
- 【C++ Primer】基本语言