当前位置 博文首页 > zcy_wxy的博客:230. 二叉搜索树中第K小的元素

    zcy_wxy的博客:230. 二叉搜索树中第K小的元素

    作者:[db:作者] 时间:2021-07-21 21:42

    ?主要思路是:

    根据二叉搜索树中节点左小右大的特点,使用中序遍历的方式,即可顺序找到第k小元素。

    代码如下:

    package easy;
    
    import tree.TreeNode;
    
    
    public class KthSmallest {
        private TreeNode tarNode;
        private int t_k;
        public int kthSmallest(TreeNode root, int k) {
            //二叉树搜索树:左小右大
            t_k=k;
            inOrder(root);
            return tarNode.val;
        }
    
        private void inOrder(TreeNode root) {
            if (t_k==0){
                return;
            }
    
            if (root.left!=null){
                inOrder(root.left);
            }
            t_k--;
            if (t_k==0){
                tarNode=root;
                return;
            }
            if (root.right!=null){
                inOrder(root.right);
            }
        }
    }
    

    ?

    cs
    下一篇:没有了