Kth Smallest Element in a BST
来源:互联网 发布:形容网络不好的说说 编辑:程序博客网 时间:2024/06/07 02:57
题意:
给定一棵二叉查找树,找出第k大的元素;
分析:
二叉查找树中序遍历正好是有序的,找到第k个即可
/** * 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) { Stack<TreeNode> stack = new Stack<TreeNode>(); int cnt = 0; TreeNode p = root, q = null; while(p != null || !stack.empty()){ if(p != null){ stack.push(p); p = p.left; } else{ p = stack.peek(); stack.pop(); cnt++; if(cnt == k){ q = p; break; } p = p.right; } } return q.val; }}
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
- <网络编程培训之一> 编程实现IP/TCP/UDP报文
- "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")"的分析
- Hadoop Linux下txt文件乱码
- 控件的使用
- LeetCode之Palindrome Partitioning
- Kth Smallest Element in a BST
- [LeetCode]171 Excel Sheet Column Number
- HTML样式
- OpenStack在计算节点安装Docker遇到的问题
- ARC小解(一)
- LoaderManager杂记
- MySQL——存储过程
- easyUI学习记录
- HDU 5480 Conturbatio