Where am i wrong? getting runtime error?


  • 1
    G
    /**
     * 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* invertTree(TreeNode* root) {
            if(!root)return root;
            root->left=invertTree(root->right);
            root->right=invertTree(root->left);
            return root;
        }
    };

  • 1
    D

    You used a wrong left pointer in the second statement,

    root->left=invertTree(root->right);
        root->right=invertTree(root->left); // here you used the modified left pointer, not the original one
    

    My version

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            TreeNode *temp;
            if(root)
            {
                temp = root->right;
                root->right = invertTree(root->left);
                root->left  = invertTree(temp);
            }
            return root;
        }
    };
    

Log in to reply
 

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