Binary Search Tree find Kth largest Node 二叉搜索树的第k大节点

Binary Search Tree find Kth largest Node 二叉搜索树的第k大节点

给一棵二叉树搜索树,找出树的第k个大的节点。

输入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
输出: 4输入:root = [1,2,3,4,5,6]
输出:6

思路

二叉树搜索树,二叉排序树 统称BST

左子树上的节点比右子树的节点值小,通过中序遍历,得到的是一个有序的数列

使用递归统计右子树节点数为cnt,如果k= cnt+1;说明根节点就是第k大的节点。如果k<=cnt,那么第k大的节点就在右子树,否则就在左子树中第 k- cnt -1.

递归

public int getcount(TreeNode root){
    
    
        if(root == null){
    
    
            return 0;
        }
        int r=0 ,l =0;
        if(root.right!=null){
    
    
            r = getcount(root.right);
        }
        if(root.left!=null){
    
    
            l = getcount(root.left);
        }
        return l+r+1;
    }
    public int kthLargest(TreeNode root, int k){
    
    
        if(root == null){
    
    
            return 0;
        }
        int cnt =  getcount(root.right);
        if(k ==cnt+1){
    
    
            return root.val;
        }
        if(k<=cnt){
    
    
            return kthLargest(root.right,k);
        }
        return kthLargest(root.left,k-cnt-1);
    }

Tag

tree

Guess you like

Origin blog.csdn.net/edisonzhi/article/details/115794901