My C++ codes (recursive and nonrecursive)


  • 3
    D

    Non-recursive version, do breadth-first processing, use a queue to save the current level un-processed non-NULL node. Everytime, switch the left and right pointers of the front nodes, pop it out, and add its non-null children to the queue.

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

    Recursive 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.