Invert Binary Tree

反转二叉树,没仔细看题,层序遍历的思想,写完WA了,一看错误数据,尴尬的反转错了

Invert Binary Tree_第1张图片

    TreeNode* invertTree(TreeNode* root) {
        queue q;
        TreeNode* newroot = root;
        q.push(root);
        while(!q.empty()){
            TreeNode* temp = q.front();
            if(temp == NULL){
                return NULL;
            }
            q.pop();
            if(temp->left != NULL && temp->right !=NULL){
                int tt = temp->left->val;
                temp->left->val = temp->right->val;
                temp->right->val = tt;
                q.push(temp->left);
                q.push(temp->right);
            }
        }
        return newroot;
    }
 emmm ..重写

    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL){
            return NULL;
        }
        queue q;
        TreeNode* newroot = root;
        q.push(root);
        while(!q.empty()){      
            TreeNode* temp = q.front();
            q.pop();
            TreeNode* left = temp->left; 
            temp->left = temp->right;
            temp->right = left;   
            if(temp->left)
                q.push(temp->left);
            if(temp->right)
                q.push(temp->right);

        }
        return newroot;
    }


你可能感兴趣的:(LeetCode)