Invert Binary Tree @LeetCode

PROBLEM :

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Recursive Solution )
--------------------------------------------------------------------------------

 /**
 * 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==NULL)
            return root ;
     
        TreeNode* l=invertTree(root->left) ;
        TreeNode* r=invertTree(root->right) ;
     
        root->left=r ;
        root->right=l ;
        return root ;
    }
};

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Iterative Solution )
--------------------------------------------------------------------------------

/**
 * 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==NULL)
            return root ;
         
        queue<TreeNode*> que ;
        que.push(root) ;
     
        while(!que.empty()){
            TreeNode* node=que.front() ;
            que.pop() ;
         
            TreeNode* temp ;
            temp=node->left ;
            node->left=node->right ;
            node->right=temp ;
         
            if(node->left)
                que.push(node->left) ;
            if(node->right)
                que.push(node->right) ;
        }
        return root ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )