/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Stack<Integer> stack1 = new Stack<>();
public int kthLargest(TreeNode root, int k) {
if(root==null){
return -1;
}
//二叉搜索书是排好序的树 可以转换为中序遍历 就是从小到大排列
//把遍历出的节点数值存储到栈中 拿到k就行了。
midPrint(root);
int temp=0;
for(int i =0 ; i<k;i++){
if(stack1.size()==0){
return -1;
}
temp=stack1.pop();
}
return temp;
}
//递归的方法
public void midPrint(TreeNode node){
if(node.left!=null){
midPrint(node.left);
}
stack1.push(node.val);
if(node.right!=null){
midPrint(node.right);
}
}
}
较慢 思考更高效率的方法:
/**
* 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) {
if(root==null){
return -1;
}
Stack<TreeNode> stack1 = new Stack<>();
TreeNode node=root;
int count=0;
//二叉搜索树是排好序的树 可以转换为中序遍历 就是从小到大排列
//倒着遍历二叉树 遍历k个值。
while(stack1!=null || node!=null){
while(node!=null){
stack1.push(node);
node=node.right;
}
if(node==null){
node=stack1.pop();
if(++count==k){
return node.val;
}
node=node.left;
}
}
return -1;
}
}
效率一些的方法:使用中序输出的倒序,就是从大到小排列。也不用记录每一个数是多少。只需要设置一个count计数,等到count==k的时候获取那个值就可以了。 如果k输入混乱,比如k小于0或者大于树中节点数目,那么还需要加入判断,这个比较简单忘了写了。