CC-19 : Convert Binary Tree to LinkedList.
Description:
Convert a Binary Tree to a Linked List. To do this, the right child link of Binary Tree will be used as nextNode link of Linked List. The left children of nodes will be added to Linked List as right children and left child link will be set as null. Given a Binary Tree, convert it to LinkedList using above described logic.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Bfs traversal Orig Tree : 4,5,7,6,78,14,33,8,16,18,9 After converting to LinkedList Bfs traversal : 4,5,6,33,78,7,14,8,16,18,9 |
Pseudocode:
| We will use PrevNode member variable to store a reference of previous node that was processed. |
Method convertToLinkedList(TreeNode node):
| If root node is null, return. |
| Else:
Recursively call convertToLinkedList() method with node’s right child as input parameter.
Recursively call convertToLinkedList() method with node’s left child as input parameter.
Set right child of node to PrevNode.
Set left child of node to null.
Set prevNode to node.
|
Code:
public class BinTreeToLinkedList{
private BinTreeNode prevNode=null;
private void convertToLinkedList(BinTreeNode node) {
if (node==null) {return;}
convertToLinkedList(node.getRightChild());
convertToLinkedList(node.getLeftChild());
node.setRightChild(prevNode);
node.setLeftChild(null);
prevNode=node;
}
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |