[GFG] leftmost and rightmost nodes of binary tree
https://practice.geeksforgeeks.org/problems/leftmost-and-rightmost-nodes-of-binary-tree/1unknown
c_cpp
a year ago
1.0 kB
8
Indexable
Never
// AMAN JAIN MCA 1st YEAR 2nd SEM // time O(N), space O(number of nodes in a level) // Approach: Basic level order traversal using level separators void printCorner(Node *root) { vector<int> currentLevel; queue<Node*> nodeQueue; nodeQueue.push(root); nodeQueue.push(NULL); while(!nodeQueue.empty()) { Node* currentNode = nodeQueue.front(); nodeQueue.pop(); if(currentNode == NULL) { cout << currentLevel[0] << " "; if(currentLevel.size() > 1) { cout << currentLevel[currentLevel.size() - 1] << " "; } currentLevel = vector<int>(); if(nodeQueue.size()) { nodeQueue.push(NULL); } } else { currentLevel.push_back(currentNode -> data); if(currentNode -> left) { nodeQueue.push(currentNode -> left); } if(currentNode -> right) { nodeQueue.push(currentNode -> right); } } } }