How you print left view of binary tree?


#1

How you print left view of binary tree?


#2

static void printLeftViewOfBinaryTree(treeNode *rootNode) {

//queues to store current and next level nodes
queue<treeNode*> Q1;
queue<treeNode*> Q2;

Q1.push(rootNode);

//print rootNode node
cout << rootNode->val << endl;

while (!Q1.empty()) {

	treeNode * temp = Q1.front();
	Q1.pop();

	if (temp->leftChild)
		Q2.push(temp->leftChild);
	if (temp->rightChild)
		Q2.push(temp->rightChild);

	if (Q1.empty() && !Q2.empty()) {
		//print the first element of each level
		cout << Q2.front()->val << endl;
		//move nodes form next level to current level
		swap(Q1, Q2);
	}

}

}


#3

let us consider the below given binary tree .
1
2 3
4 5 6
8 9
10
so now we want to print the print the left view of binary tree.

node 1 is left-most node for level 0.
node 2 is left-most node for level 1.
node 4 is left-most node for level 2.
node 8 is left-most node for level 3.
node 10 is left-most node for level 4.

And therefore left view for this tree is 1,2,4,8,10

program:

public void printLeftNRightViewOfBT(BinaryNode node) {
Queue queue = new LinkedList();
BinaryNode LS = new BinaryNode(null);
queue.add(node);
queue.add(LS);

// left view and right view arrays
List<BinaryNode> leftView = new ArrayList<BinaryNode>();
List<BinaryNode> rightView = new ArrayList<BinaryNode>();
leftView.add(node);

while (!queue.isEmpty()) {
    BinaryNode currentNode = queue.remove();
    if (!queue.isEmpty() && currentNode.equals(LS)) {
        leftView.add(queue.peek());
        queue.add(LS);
    }
    if (!queue.isEmpty() && queue.peek().equals(LS)) {
        rightView.add(currentNode);
    }
    if (currentNode.left != null) {
        queue.add(currentNode.left);
    }
    if (currentNode.right != null) {
        queue.add(currentNode.right);
    }
}

// print views
printViews(leftView);
printViews(rightView);

}

this program gives the output to print both left and right views of binary tree.