Kth Smallest Element in a BST
来源:互联网 发布:程序员工作体会 编辑:程序博客网 时间:2024/06/05 17:44
Given a binary search tree, write a function kthSmallest to find the kth smallest
element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
找到二叉搜索树中的第k小的元素。
使用栈,如果有左子树,入栈,否则出栈,k--,k=0则当地节点就是要找的节点,
否则寻找右子树。
因为最小的点在最左下,所以一直操作左子树。
public class Solution { public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> stack=new Stack<TreeNode>();TreeNode p=root;while(p!=null||!stack.isEmpty()){if(p!=null){stack.push(p);p=p.left;}else{TreeNode t=stack.pop();k--;if(k==0)return t.val;p=t.right;}}return 0; }}
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
- java读入txt时去除两端的空格
- <context:component-scan>使用说明
- ubuntu下zsh安装使用
- HTML CSS属性overflow、white-space、text-overflow
- 在命令行下进行Oracle用户解锁
- Kth Smallest Element in a BST
- 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
- Java之美[从菜鸟到高手演变]之智力题【史上最全】
- 数据库设计三大范式
- 短信黑名单app接收短信优先级权限设置
- 龙星计划机器学习笔记
- C语言的结构体、联合和枚举
- VC WIFI常用API地址
- VC 双缓冲绘图