diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/README.md b/solution/0500-0599/0538.Convert BST to Greater Tree/README.md index ee47bd93981af..77b1b478eea5e 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/README.md +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/README.md @@ -77,7 +77,18 @@ ```java - +class Solution { + int add = 0; + public TreeNode convertBST(TreeNode root) { + if (root != null) { + convertBST(root.right); + root.val += add; + add = root.val; + convertBST(root.left); + } + return root; + } +} ``` ### **...** diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md b/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md index 33591ef4993e9..bef0d76b00071 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md @@ -108,7 +108,18 @@ ### **Java** ```java - +class Solution { + int add = 0; + public TreeNode convertBST(TreeNode root) { + if (root != null) { + convertBST(root.right); + root.val += add; + add = root.val; + convertBST(root.left); + } + return root; + } +} ``` ### **...** diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md index 1849cd428ee48..e3b2a8e195fba 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md @@ -77,7 +77,23 @@ ```java - +class Solution { + private int max = 0; + + public TreeNode bstToGst(TreeNode root) { + if (root == null) return new TreeNode(0); + int temp = bstToGst(root.right).val; + root.val += (temp > max ? temp : max); + max = root.val > max ? root.val : max; + if (root.left != null) { + int temp2 = bstToGst(root.left.right).val; + root.left.val += max > temp2 ? max : temp2; + max = max > root.left.val ? max : root.left.val; + bstToGst(root.left.left); + } + return root; + } +} ``` ### **...** diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md index 996c32ac0055c..51c97562d6b1a 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md @@ -108,7 +108,23 @@ ### **Java** ```java - +class Solution { + private int max = 0; + + public TreeNode bstToGst(TreeNode root) { + if (root == null) return new TreeNode(0); + int temp = bstToGst(root.right).val; + root.val += (temp > max ? temp : max); + max = root.val > max ? root.val : max; + if (root.left != null) { + int temp2 = bstToGst(root.left.right).val; + root.left.val += max > temp2 ? max : temp2; + max = max > root.left.val ? max : root.left.val; + bstToGst(root.left.left); + } + return root; + } +} ``` ### **...**