LeetCode226翻转二叉树

class Solution {
public:
    TreeNode* invertTree(TreeNode *pRoot) {
        if(pRoot==nullptr)    return nullptr;
        queue<TreeNode*> qu;
        qu.push(pRoot);
        while(!qu.empty()){
            TreeNode* front=qu.front();
            TreeNode* temp=front->left;
            front->left=front->right;
            front->right=temp;
            qu.push(front->left);
            qu.push(front->right);
            qu.pop();
        }
        return pRoot;
    }
};

用front的left和right漏掉对front的判空

class Solution {
public:
    TreeNode* invertTree(TreeNode *pRoot) {
        if(pRoot==nullptr)    return nullptr;
        queue<TreeNode*> qu;
        qu.push(pRoot);
        while(!qu.empty()){
            TreeNode* front=qu.front();
            if(front){
                TreeNode* temp=front->left;
                front->left=front->right;
                front->right=temp;
                qu.push(front->left);
                qu.push(front->right);
            }
            qu.pop();  无论空节点入不入队都要删掉
        }
        return pRoot;
    }
};

或者

class Solution {
public:
    TreeNode* invertTree(TreeNode *pRoot) {
        if(pRoot==nullptr)    return nullptr;
        queue<TreeNode*> qu;
        qu.push(pRoot);
        while(!qu.empty()){
        	TreeNode* front=qu.front();
			TreeNode* temp=front->left;
			front->left=front->right;
			front->right=temp;
			if(front->left)	qu.push(front->left);
			if(front->right)	qu.push(front->right);  //空节点不入队
			qu.pop(); 
        }
        return pRoot;
    }
};

你可能感兴趣的:(算法)