CC-17 : Create Mirror Binary Tree.
Description:
In a mirror Binary Tree, all nodes have their left and right child nodes interchanged. Given a Binary Tree, find and return the mirror Binary Tree.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Bfs traversal Orig Tree: 4,5,7,6,78,14,33,8,16,18,9 Mirror Bfs traversal: 4,7,5,14,78,6,16,8,33,18,9 |
Pseudocode:
Method mirrortree(root):
| If root node is null, return null. |
| Set reference of root’s right child to root’s left child member variable. |
| Set reference of root’s left child to root’s right child member variable. |
| Recursively call mirrortree() method with roots’ left child as input parameter. |
| Recursively call mirrortree() method with roots’ right child as input parameter. |
Code:
public void mirrorTree(BinTreeNode root) {
if (root==null) {return;}
BinTreeNode temp=root.getLeftChild();
root.setLeftChild(root.getRightChild());
root.setRightChild(temp);
mirrorTree(root.getLeftChild());
mirrorTree(root.getRightChild());
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |