c++ in-order traversal


  • 0
    T
    class Solution {
    public:
        int treeSum(TreeNode *node) {
            if (!node) return 0;
            return node->val + treeSum(node->left) + treeSum(node->right);
        }
        void convert(TreeNode *root, int &presum, int sum) {
            if (!root) return;
            convert(root->left, presum, sum);
            root->val += (sum - (presum += root->val));
            convert(root->right, presum, sum);
        }
        TreeNode* convertBST(TreeNode* root) {
            int sum = treeSum(root), presum = 0;
            convert(root, presum, sum);
            return root;
        }
    };
    

Log in to reply
 

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