[leetcode]230. Kth Smallest Element in a BST

    xiaoxiao2021-03-25  101

    BST二叉搜索树,性质:每个节点的左孩子小于根节点,右孩子大于根节点

    根据BST的性质,以及数组中第k大数的思想(QuickSelect分割思想),

    先计算当前结点的左孩子节点的个数,与k比较

    如果小于k-1(考虑当前节点),则第k大的数在右孩子节点

    如果大于k-1,则第k大的数载左孩子节点

    如果等于k-1,则返回当前结点的值

    public int kthSmallest(TreeNode root, int k) { int count = countNode(root.left); if(count==k-1){ return root.val; }else if(count<k-1){ return kthSmallest(root.right,k-1-count); }else if(count>k-1){ return kthSmallest(root.left,k); } return -1; } public int countNode(TreeNode root){ if(root==null){ return 0; } return 1+countNode(root.left)+countNode(root.right); }

    转载请注明原文地址: https://ju.6miu.com/read-26277.html

    最新回复(0)