树第4天

64 阅读1分钟

第4天

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

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        record = k;
        find(root);
        return res;
    }

    int res;
    int record;

    void find(TreeNode root){
        if(root == null)
            return;

        find(root.left);
        record--;
        if(record == 0){
            res = root.val;
            return;
        }
        
        find(root.right);
    }
}

538. 把二叉搜索树转换为累加树

class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        exchange(root);
        return root;
    }

    void exchange(TreeNode root){
        if(root == null)
            return;
        exchange(root.right);

        root.val = sum += root.val;
        
        exchange(root.left);
    }
}