230. 二叉搜索树中第K小的元素 ( 中序遍历 )

LeetCode:230. 二叉搜索树中第K小的元素

在这里插入图片描述

二叉搜索树

中序遍历 >> 遍历结果就是从小到大的.


当反着进行中序遍历的时候,就是从大到小


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

}



猜你喜欢

转载自blog.csdn.net/qq_43765535/article/details/112778978
今日推荐