[leetcode]230. Kth Smallest Element in a BST

来源:互联网 发布:百度软件开发工程师 编辑:程序博客网 时间:2024/06/06 00:34

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);    }


0 0
原创粉丝点击