leetcode538_把二叉搜索树转换为累加树

这个东西本质上就是一个搜索+存储,只要把遍历的每一个val存下来就行了。
你能意识到这个东西是对右子树的中序遍历,如果实在不知道怎么写就先写注释。
而且也不一定非要一口气写成一个唯一函数,熟能生巧熟能生巧,先熟再巧。

class Solution {
    private int num = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root == null) return null;
        convertBST(root.right);
        root.val += num;
        num = root.val;
        convertBST(root.left);
        return root;
    }
}
posted @ 2022-04-19 11:56  明卿册  阅读(15)  评论(0编辑  收藏  举报