[leetcode]230. Kth Smallest Element in a BST
来源:互联网 发布:百度软件开发工程师 编辑:程序博客网 时间:2024/06/06 00:34
BST二叉搜索树,性质:每个节点的左孩子小于根节点,右孩子大于根节点
根据BST的性质,以及数组中第k大数的思想(QuickSelect分割思想),
先计算当前结点的左孩子节点的个数,与k比较
如果小于k-1(考虑当前节点),则第k大的数在右孩子节点
如果大于k-1,则第k大的数载左孩子节点
如果等于k-1,则返回当前结点的值
public int kthSmallest(TreeNode root, int k) { int count = countNode(root.left); if(count==k-1){ return root.val; }else if(count<k-1){ return kthSmallest(root.right,k-1-count); }else if(count>k-1){ return kthSmallest(root.left,k); } return -1; } public int countNode(TreeNode root){ if(root==null){ return 0; } return 1+countNode(root.left)+countNode(root.right); }
0 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- HDU 4727 The Number Off of FFF
- opencv入门学习之七:罗伯特Robert变换和Sobel变换锐化图像
- Log4j学习总结
- [Leetcode] #200 Number of Islands
- 互信息和信息熵
- [leetcode]230. Kth Smallest Element in a BST
- 飞花的糖果
- 注解框架---AndroidAnnotations
- poj 1150 The Last Non-zero Digit(阶乘取模运算的简单性质及递归技巧)
- C++ string split
- 2017-04-04 水题信心 03选美比赛
- 新人报道
- 【图像处理】提取图片中的交点数据 [已删除]
- Unity GUI的使用1