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

1.题目描述:

给出二叉搜索树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点node的新值等于原树中大于或等于node.val的值之和。

2.中序遍历:

首先中序遍历用集合记录所有节点的值,再通过中序遍历将每个节点的值更新,这种方法将集合排序后可适用所有二叉树。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode convertBST(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inOrder(root, list);
        inOrder1(root, list);
        return root;
    }

    public void inOrder(TreeNode root, List<Integer> list) {
        if (root == null) return;
        inOrder(root.left, list);
        list.add(root.val);
        inOrder(root.right, list);
    }

    public void inOrder1(TreeNode root, List<Integer> list) {
        if (root == null) return;        
        inOrder1(root.left, list);
        int index = list.indexOf(root.val);
        for (int i = index + 1; i < list.size(); i++) {
            root.val += list.get(i);
        }
        inOrder1(root.right, list);
    }
}

3.反中序遍历:

正常的中序遍历无法累加后面比当前节点值大的节点,所以需要反中序遍历,也就是right—>root—>left,这样可以边遍历边记录比自己大的节点和,代码如下:

class Solution {
    private TreeNode pre = null;
    public TreeNode convertBST(TreeNode root) {
        reverseInOrder(root);
        return root;
    }

    public void reverseInOrder(TreeNode root) {
        if (root == null) return;
        reverseInOrder(root.right);
        if (pre != null) root.val += pre.val;
        pre = root;
        reverseInOrder(root.left);
    }
}

4.迭代反中序遍历:

二叉树迭代的中序遍历见leetcode94. 二叉树的中序遍历

class Solution {
    public TreeNode convertBST(TreeNode root) {
        if (root == null) return root;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode temp = root;
        TreeNode pre = null;
        while (temp != null || !stack.isEmpty()) {
            if (temp != null) {
                stack.push(temp);
                temp = temp.right;
            } else {
                temp = stack.pop();
                if (pre != null) temp.val += pre.val;
                pre = temp;
                temp = temp.left;   
            }
        }
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值