1. 程式人生 > 其它 >【資料結構】演算法 Binary Search Tree find Kth largest Node 二叉搜尋樹的第k大節點

【資料結構】演算法 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