Advertisement
nikunjsoni

1038

Apr 22nd, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13.     int sum = 0;
  14. public:
  15.     TreeNode* bstToGst(TreeNode* root) {
  16.         dfs(root);
  17.         return root;
  18.     }
  19.    
  20.     void dfs(TreeNode* root){
  21.         if(!root) return;
  22.         dfs(root->right);
  23.         sum += root->val;
  24.         root->val = sum;
  25.         dfs(root->left);
  26.     }
  27.    
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement