230. The K-th smallest element in the binary search tree (middle-order traversal)

LeetCode: 230. The Kth smallest element in the binary search tree

Insert picture description here

Binary search tree

Mid-order traversal >> The traversal results are from small to large.


When traversing in reverse order, it is from largest to smallest


AC Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    
    int cnt = 0, ans = 0;
    public int kthSmallest(TreeNode root, int k) {
    
    
        // 中序遍历 左 根 右
        if(root.left != null)
            ans = kthSmallest(root.left, k);
        //根
        cnt++;
        if(cnt == k) return root.val;

        if(root.right != null)
            ans = kthSmallest(root.right, k);

        return ans;
    }

}



Guess you like

Origin blog.csdn.net/qq_43765535/article/details/112778978