Algorithms—230.Kth Smallest Element in a BST
2015-08-25 10:11
330 查看
思路:每次进来数一下左侧的节点数数,如果恰好比左侧节点数多1,则返回根节点,小于在左侧,大于在右侧。
/** * 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) { int left=f(root.left); if (k==left+1) { return root.val; } if (k<=left) { return kthSmallest(root.left,k); } return kthSmallest(root.right,k-left-1); } public int f(TreeNode root){ if (root!=null) { return 1+f(root.left)+f(root.right); } return 0; } }
相关文章推荐
- django之model中的Field类型
- light oj 1057 Collecting Gold(状态压缩dp)
- django orm基本使用策略
- leetcode: (263) Ugly Number
- [Golang] 从零开始写Socket Server(4):将运行参数放入配置文件(XML/YAML)
- mongoose模块自动生成_id
- Google Earth谷歌地球卫片下载器--可下载全球历史卫星,无偏移、高精度
- [c] poj1003 hangover
- wordpress第一天
- leetcode: (171) Excel Sheet Column Number
- Set a static file on django
- 服务程序中侦测用户logon和logoff消息
- Go web之旅(路由篇)
- Google Alphabet
- Dragon Balls 3635 (并查集求深度) 好题
- Round A APAC Test 2016 Problem A. Googol String
- STL - vector algorithm
- google hosts google翻译ip
- 杭电3635-Dragon Balls-并查集之路径压缩
- django RESTful研究一环境搭建和理解RESTful