Kth Smallest Element in a BST
来源:互联网 发布:乐乎公寓公益西桥 编辑:程序博客网 时间:2024/06/04 23:33
解题思路:按树的中序遍历的方式,利用栈实现,第k个出栈的节点即是所求的。
Java代码实现:
/** * 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) { TreeNode p=new TreeNode(0); p=root; Stack sk=new Stack(); sk.push(p); while(p.left!=null){ sk.push(p.left); p=p.left; } int i=0; while(!sk.isEmpty()){ TreeNode q=new TreeNode(0); q=(TreeNode)sk.pop(); i++; if(i==k) return q.val; if(q.right!=null) { p=q.right; sk.push(p); while(p.left!=null){ sk.push(p.left); p=p.left; } } } return 0; }}
原题题目:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
0 0
- #leetcode#Kth Smallest Element in a BST
- 230.Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- 2.1 从链表中移除重复结点
- 2015-0908-osg学习历程7
- 面向对象基础
- 扩展性与存储限制问题
- swift学习笔记(一)
- Kth Smallest Element in a BST
- java web服务器cpu占用过高的处理
- Qt问题综合
- unity5 动画系统Mecanim事件快速入门 区分animation和animator不再混淆
- PL/SQL中cursor(光标/游标)的用法
- 跟着Vamei大神-02了解play
- 疯狂猜歌实现(2)—— 实现唱片布局以及播放动画
- 自定义View时出现:"android.view.InflateException: Binary XML file line报错问题"
- 24点计算 算法