leetcode230. 二叉探索ツリーのK番目の小さい要素(Kth Smallest Element in a BST)

684 ワード

二叉探索ツリーを指定し、関数kthSmallestを記述してk番目の最小要素を検索します.
二叉探索ツリーの場合、前シーケンス中シーケンス遍歴は秩序ある探索であるため、前シーケンス中シーケンス遍歴に探索回数を記録するだけで済むため、比較的容易に実現できる
public static int num = 0;
    public static int remain = 0;
    public int kthSmallest(TreeNode root, int k) {
        remain = k;
        visitK(root);
        return num;
    }
    private void visitK(TreeNode root){
        if(root == null){
            return;
        }
        if(root.left != null){
            visitK(root.left);
        }
        remain--;
        if(remain == 0){
            num = root.val;
            return;
        }
        if(root.right != null){
            visitK(root.right);
        }
    }