Created
April 7, 2018 18:10
-
-
Save shixiaoyu/bc0d8dc93e430cf3d889eff6941df827 to your computer and use it in GitHub Desktop.
leetcode problem 538 https://leetcode.com/problems/convert-bst-to-greater-tree/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is the naive idea to serialize the tree into an array, modify the values, but keep the left/right child | |
// intact, but this uses extra O(N) space and O(N) time | |
public void serializeTreeSum(TreeNode node) { | |
List<TreeNode> nodes = new ArrayList<>(); | |
this.inorderTraversal(node, nodes); | |
// nodes is sorted ascendingly after inorder traversal, keep a rolling sum | |
int rollingSum = 0; | |
for (int i = nodes.size() - 1; i >= 0; i--) { | |
nodes.get(i).val = nodes.get(i).val + rollingSum; | |
rollingSum = nodes.get(i).val; | |
} | |
} | |
public void inorderTraversal(TreeNode node, List<TreeNode> nodes) { | |
if (node == null) { | |
return; | |
} | |
this.inorderTraversal(node.left, nodes); | |
nodes.add(node); | |
this.inorderTraversal(node.right, nodes); | |
} | |
public TreeNode convertBST(TreeNode root) { | |
this.serializeTreeSum(root); | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment