Um momento
Leetcode / 897. Increasing Order Search Tree

Pick a programming language:

Here is the source code for the solution to this problem.

/**
 * 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 increasingBST(TreeNode root) {
        TreeNode curr = root;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        List<TreeNode> list = new LinkedList<TreeNode>();

        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            else {
                curr = stack.pop();
                list.add(curr);
                curr = curr.right;
            }
        }

        for (int i = 0; i < list.size(); i++) {
            TreeNode currentNode = list.get(i);

            currentNode.left = null;
            // the following conditional is actually not even necessary if
            // your loop condition is < list.size() - 1, since you know for
            // sure the rightmost Node, with the highest value, will not
            // have a right child. 
            if (i < list.size() - 1) {
                currentNode.right = list.get(i + 1);
            }
            else {
                currentNode.right = null;
            }
        }

        return list.get(0);
    }
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: