LeetCode 538 (LintCode 661) Convert BST to Greater Tree

54 篇文章 2 订阅
18 篇文章 0 订阅

思路

“反中根“遍历。从BST的最右节点开始遍历,然后记录当前的节点和,后面的每个节点只要加上这个和即可;在原树上修改。
将中根遍历的left和right访问顺序反过来,使用一个全局变量sum记录当前的和。整体思路类似分治算法。

代码

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of binary tree
     * @return: the new root
     */
    
    int sum = 0;
    
    public TreeNode convertBST(TreeNode root) {
        // write your code here
        dfs(root);
        return root;
    }
    
    public void dfs(TreeNode root) {
        if(root == null) return;
        
        dfs(root.right);
        root.val += sum;
        sum = root.val;
        dfs(root.left);
    }
}

复杂度

时间复杂度O(n), 因为每个节点有且仅有一次访问
空间复杂度O(h)=O(logn), 因为用到了递归栈,栈的大小是树的高度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值