【两次过】Lintcode 661. 把二叉搜索树转化成更大的树

本文介绍了一种算法,将二叉搜索树(BST)转换为累加树,其中每个节点的值更新为原始树中大于等于其值的所有节点值之和。提供了两种实现方法:递归和非递归。递归方法使用深度优先遍历,而非递归方法则利用栈进行迭代。

给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值的节点值之和(包括该节点)。

样例

Given a binary search Tree `{5,2,13}`:

              5
            /   \
           2     13

Return the root of new tree

             18
            /   \
          20     13

解题思路1:

先右子树再根节点再左子树的形式递归,其中设置全局变量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
     */
    public TreeNode convertBST(TreeNode root) {
        // write your code here
        dfs(root);
        
        return root;
    }
    
    private int sum = 0;
    
    private void dfs(TreeNode root){
        if(root == null)
            return;
            
        dfs(root.right);
        sum += root.val;
        root.val = sum;
        dfs(root.left);
    }
}

解题思路2:

非递归方式。

/**
 * 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
     */
    public TreeNode convertBST(TreeNode root) {
        // write your code here
        if(root == null)
            return null;
            
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        int sum = 0;
        
        while(node != null || !stack.isEmpty()){
            while(node != null){
                stack.push(node);
                node = node.right;
            }
            
            node = stack.pop();
            sum += node.val;
            node.val = sum;
            node = node.left;
        }
        
        return root;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值