Beat 100% C++


  • 2
    R
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* convertBST(TreeNode* root) {
            stack<TreeNode*> s;
            TreeNode* cur = root;
            int sum = 0;
            while(!s.empty() || cur) {
                if(cur){
                    s.push(cur);
                    cur = cur->right;
                }
                else {
                    cur = s.top()->left;
                    int tmp = sum;
                    sum += s.top()->val;
                    s.top()->val += tmp;
                    s.pop();
                }
            }
            return root;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.