[LeetCode] 538. The binary search tree into the tree ☆ accumulation (deformation preorder)

The binary search tree into a tree cumulative

description

Given a binary search tree (Binary Search Tree), it is converted into accumulated trees (Greater Tree), such that the value of each node is the original value of the node plus all its node value is greater than the sum.

E.g:

Input: binary search tree:
5
/ \
2 13

Output: convert accumulated tree:
18
/ \
20 13

Resolve

Standard traversal sequence, then the anti-traverse, the value + value before each node = node.

Code

Silly method

First tree, all around the exchange, re-order traversal criteria, then switching back around.

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);
    }

Modification inorder traversal - Stack Iterative

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;
    }

Modification inorder traversal - Recursive

    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;
    }

 

Guess you like

Origin www.cnblogs.com/fanguangdexiaoyuer/p/12063349.html