Why it give me a Runtime Error,but my computer doesn't


  • 0
    J
    /**
     * 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->left!=NULL){
                swapTree(root);
                invertTree(root->left);
                invertTree(root->right);
            }
        }
        void swapTree(TreeNode *node){
            TreeNode *tem=node->left;
            node->left=node->right;
            node->right=tem;
        }
    };
    

    //when Running in my computer,it can get a right result.


  • 1
    T

    You did't return the root.

    TreeNode* invertTree(TreeNode* root) {
        if(root->left!=NULL){
            swapTree(root);
            invertTree(root->left);
            invertTree(root->right);
        }
        return root;              // you should add this line
    }

  • 0
    J

    oh yes !thank you, and I should change root->left!=NULL to root!=NULL


  • 0
    J

    I also have some problem,please help me, thank you very much!
    can I make the function have a void return , I thank return root is useless for my code.
    and in fact this code can run in my compute and give me an right result.


Log in to reply
 

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