661 - Convert BST to Greater Tree

本文介绍了一种巧妙的二叉树转换方法,通过右根左的中序遍历来实现节点值的累加更新。文章重点讨论了递归与非递归两种实现方式,并强调了在非递归方法中全局变量的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5.9

很巧妙地做法,采用右根左的中序遍历。

需要注意的是,采用非递归的方法时,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
        if(root == null){
            return root;
        }
        inOrder1(root);
        return root;
    }
    // 采用 右根左的遍历顺序 - 非递归的方式
    public void inOrder(TreeNode root){
        TreeNode bt = root;
        int sum = 0;
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();
        while(bt != null || !list.isEmpty()){
            while(bt != null){
                list.push(bt);
                bt = bt.right;
            }
            if(!list.isEmpty()){
                bt = list.pop();
                bt.val = bt.val + sum;
                sum = bt.val;
                bt = bt.left;
            }
        }
    }
   
    // 采用 右根左的遍历顺序 - 递归的方式
    private int sum = 0;
    public void inOrder1(TreeNode root){
        if(root == null){
            return;
        }
        inOrder1(root.right);
        root.val = root.val + sum;
        sum = root.val;
        inOrder1(root.left);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值