[LeetCode] 538. 把二叉搜索树转换为累加树 ☆(中序遍历变形)

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

描述

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

例如:

输入: 二叉搜索树:
5
/ \
2 13

输出: 转换为累加树:
18
/ \
20 13

解析

标准中序遍历,再反着遍历,每个节点的值 += 前一个节点的值。

代码

傻方法

先把树,左右全部交换,再标准中序遍历,再左右交换回来。

public TreeNode convertBST(TreeNode root) {
        if (null == root) {
            return null;
        }
        swap(root);
        TreeNode temp = root;
        int preVal = 0;
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || null != temp) {
            if (null != temp) {
                stack.push(temp);
                temp = temp.left;
            } else {
                TreeNode curNode = stack.pop();
                curNode.val += preVal;
                preVal = curNode.val;
                temp = curNode.right;
            }
        }
        return root;
    }

    public void swap(TreeNode root) {
        if (null == root) {
            return;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        swap(root.left);
        swap(root.right);
    }

中序遍历变形--栈迭代

public TreeNode convertBST(TreeNode root) {
        if (null == root) {
            return null;
        }
        TreeNode temp = root;
        int preVal = 0;
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || null != temp) {
            if (null != temp) {
                stack.push(temp);
                temp = temp.right;
            } else {
                TreeNode curNode = stack.pop();
                curNode.val += preVal;
                preVal = curNode.val;
                temp = curNode.left;
            }
        }
        return root;
    }

中序遍历变形--递归

    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root != null) {
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
        }
        return root;
    }

猜你喜欢

转载自www.cnblogs.com/fanguangdexiaoyuer/p/12063349.html