File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
Binary Search Tree to Greater Sum Tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 4 ms, faster than 61.67% of C++ online submissions for Binary Search Tree to Greater Sum Tree.
2
+ // Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Binary Search Tree to Greater Sum Tree.
3
+
4
+ /* *
5
+ * Definition for a binary tree node.
6
+ * struct TreeNode {
7
+ * int val;
8
+ * TreeNode *left;
9
+ * TreeNode *right;
10
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11
+ * };
12
+ */
13
+ class Solution
14
+ {
15
+ public:
16
+ TreeNode* bstToGst (TreeNode* root)
17
+ {
18
+ vector<int > nums;
19
+
20
+ inOrderTraversal (root, nums);
21
+
22
+ unordered_map<int , int > hashmap;
23
+ int temp = 0 ;
24
+ for (int i = nums.size () - 1 ; i >= 0 ; --i)
25
+ {
26
+ temp += nums[i];
27
+ hashmap.insert (make_pair (nums[i], temp));
28
+ }
29
+
30
+ inOrderModify (root, hashmap);
31
+ return root;
32
+ }
33
+ private:
34
+ void inOrderTraversal (TreeNode* root, vector<int >& nums)
35
+ {
36
+ stack<TreeNode*> memo;
37
+ while (root || !memo.empty ())
38
+ {
39
+ while (root)
40
+ {
41
+ memo.push (root);
42
+ root = root->left ;
43
+ }
44
+ if (!memo.empty ())
45
+ {
46
+ root = memo.top ();
47
+ memo.pop ();
48
+
49
+ nums.push_back (root->val );
50
+
51
+ root = root->right ;
52
+ }
53
+ }
54
+ }
55
+
56
+ void inOrderModify (TreeNode* root, unordered_map<int , int >& hashmap)
57
+ {
58
+ stack<TreeNode*> memo;
59
+ while (root || !memo.empty ())
60
+ {
61
+ while (root)
62
+ {
63
+ memo.push (root);
64
+ root = root->left ;
65
+ }
66
+ if (!memo.empty ())
67
+ {
68
+ root = memo.top ();
69
+ memo.pop ();
70
+
71
+ root->val = hashmap.at (root->val );
72
+
73
+ root = root->right ;
74
+ }
75
+ }
76
+ }
77
+ };
You can’t perform that action at this time.
0 commit comments