LeetCode:二叉搜索树的第k大节点
给定一颗二叉树,返回其第K大节点。
首先的思路就是中序遍历一颗二叉树,得到的结果是有序的,然后从得到的队列中找出第K大的数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
int res=0;
Queue<Integer> queue = new LinkedList<Integer>();
midSort(root,queue,k);
int num = queue.size();
for(int i=0;i<=num-k;i++){
res = queue.remove();
}
return res;
}
public void midSort(TreeNode root,Queue<Integer> queue,int k){
if(root.left!=null){
midSort(root.left,queue);
}
queue.offer(root.val);
if(root.right!=null){
midSort(root.right,queue);
}
}
}
但是此方法效率太低,内存消耗太高。
看了其他博主的题解思路,可以进行反向的中序遍历,并观察栈中的元素和K值得比较,满足条件提前结束循环。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
int res=0;
// Queue<Integer> queue = new LinkedList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
midSort(root,stack,k);
// int num = queue.size();
// for(int i=0;i<=num-k;i++){
// res = queue.remove();
// }
res = stack.pop();
return res;
}
public void midSort(TreeNode root,Stack stack,int k){
if(root.right!=null){
midSort(root.right,stack,k);
}
//stack.push(root.val);
// k--;
// if(k<0){
// return ;
// }
if(stack.size()<k)
stack.push(root.val);
else{
return ;
}
if(root.left!=null){
midSort(root.left,stack,k);
}
}
}
上述代码的执行效率得到了提高。
LeetCode:二叉搜索树第k大节点解法
博客围绕LeetCode中求二叉搜索树第k大节点的问题展开。最初思路是中序遍历二叉树得到有序结果,再从队列中找第k大数,但效率低、内存消耗高。后参考其他博主,采用反向中序遍历,通过比较栈中元素和k值提前结束循环,提高了执行效率。
467

被折叠的 条评论
为什么被折叠?



