8-line C++ Reverse Inorder Traversal


  • 0
    /**
     * 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:
        int sum; // primitive member variable will be initialized to 0
        TreeNode* convertBST(TreeNode* root) {
            root? reverseInorder(root):(void)0;
            return root;
        }
        
        void reverseInorder(TreeNode* p) {
            p->right?reverseInorder(p->right):(void)0;
            p->val+=sum;
            sum+=(p->val-sum);
            p->left?reverseInorder(p->left):(void)0;
        }
    };
    

Log in to reply
 

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