C++ recursive right to left traversal


  • 0
    B

    remember to update the value of predecessor of root before recursively goes to left child

    /**
     * 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) {
            if(!root) return root;
            convertBST(root -> right);
            auto node = root -> right;
            while(node && node -> left) node = node -> left;
            if(node) root -> val += node -> val;
            node = root -> left;
            while(node && node -> right) node = node -> right;
            if(node) node -> val += root -> val;
            convertBST(root -> left);
            return root;
        }
    };

Log in to reply
 

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