Answers for "invert tree"

C++
4

invert a binary tree

//The Idea is to go through a post order traversal and swap the node at the end

//assume TreeNode is the tree structure 
TreeNode* invertTree(TreeNode* root) {
        
        if(root==NULL)
            return root;
        else
        {
    		
            invertTree(root->left);
            //assuming the fn did inverted everything till of left child
            invertTree(root->right);
            //assuming the fn inverted everything till of right child
            //now swap the left child and right child nodes and return the node
            TreeNode* temp=root->left;
            root->left=root->right;
            root->right=temp;
            
            return(root);
            //return the inverted node
        }
        
    }
Posted by: Guest on October-09-2021
0

mirror a binary tree

//mirror a binary tree 

void mirror(Node root){
Queue<Node> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
Node currnode=q.poll();
Node temp=currnode.left;
currnode.left=currnode.right;
currnode.right=temp;
if(currnode.left!=null){
q.add(currnode.left);
}
if(currnode.right!=null){
q.add(currnode.right);
}
}
}
Posted by: Guest on September-29-2020
-1

invert binary tree

/* 
* help pls 
* something about root idk
*/
Posted by: Guest on September-24-2021

Browse Popular Code Answers by Language