LeetCode—剑指Offer:二叉搜索树的第k大节点(中序遍历)

二叉搜索树的第k大节点(简单)

2020年9月9日

题目来源:力扣

在这里插入图片描述

解题

  • 暴力
    中序遍历,用ArrayList记录,最后输出倒数第i个节点大小
/**
 * 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) {
    
    
        List<Integer> list=new ArrayList<>();
        find(root,list);
        return list.get(list.size()-k);
    }
    private void find(TreeNode root,List<Integer> list){
    
    
        if(root==null) return;
        find(root.left,list);
        list.add(root.val);
        find(root.right,list);
    }
}

在这里插入图片描述

  • 逆中序遍历
    左根右是从小到大,右根左是从大到小,利用全局变量k来记录是否到达想要的节点,res记录结果
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    private int k,res;
    public int kthLargest(TreeNode root, int k) {
    
    
        this.k=k;
        find(root);
        return res;
    }
    private void find(TreeNode root){
    
    
        if(root == null) return;
        find(root.right);
        if(k == 0) return;
        if(--k == 0) res = root.val;
        find(root.left);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108482204