Given a complete binary tree, traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root.
Example:
Input:
18
/ \
15 30
/ \ / \
40 50 100 20
Output: 18 15 40 50 100 20 30
Approach:
- Traverse left-most nodes of the tree from top to down. (Left boundary)
- Traverse bottom-most level of the tree from left to right. (Leaf nodes)
- Traverse right-most nodes of the tree from bottom to up. (Right boundary)
We can traverse the left boundary quite easily with the help of a while loop that checks when the node doesn’t have any left child. Similarly, we can traverse the right boundary quite easily with the help of a while loop that checks when the node doesn’t have any right child.
The main challenge here is to traverse the last level of the tree in left to right order. To traverse level-wise there is BFS and order of left to right can be taken care of by pushing left nodes in the queue first. So the only thing left now is to make sure it is the last level. Just check whether the node has any child and only include them.
We will have to take special care of the corner case that same nodes are not traversed again. In the example above 40 is a part of the left boundary as well as leaf nodes. Similarly, 20 is a part of the right boundary as well as leaf nodes.
So we will have to traverse only till the second last node of both the boundaries in that case. Also keep in mind we should not traverse the root again.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node *left, *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Function to print the nodes of a complete // binary tree in boundary traversal order void boundaryTraversal(Node* root) { if (root) { // If there is only 1 node print it // and return if (!(root->left) && !(root->right)) { cout << root->data << endl; return; } // List to store order of traversed // nodes vector<Node*> list; list.push_back(root); // Traverse left boundary without root // and last node Node* L = root->left; while (L->left) { list.push_back(L); L = L->left; } // BFS designed to only include leaf nodes queue<Node*> q; q.push(root); while (!q.empty()) { Node* temp = q.front(); q.pop(); if (!(temp->left) && !(temp->right)) { list.push_back(temp); } if (temp->left) { q.push(temp->left); } if (temp->right) { q.push(temp->right); } } // Traverse right boundary without root // and last node vector<Node*> list_r; Node* R = root->right; while (R->right) { list_r.push_back(R); R = R->right; } // Reversing the order reverse(list_r.begin(), list_r.end()); // Concatenating the two lists list.insert(list.end(), list_r.begin(), list_r.end()); // Printing the node's data from the list for (auto i : list) { cout << i->data << " "; } cout << endl; return; } } // Driver code int main() { // Root node of the tree Node* root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->right->left = newNode(10); root->right->right = newNode(25); boundaryTraversal(root); return 0; } |
Python
# Python implementation of the approach from collections import deque # A binary tree node class Node: # A constructor for making a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to print the nodes of a complete # binary tree in boundary traversal order def boundaryTraversal(root): # If there is only 1 node print it and return if root: if not root.left and not root.right: print (root.data) return # List to store order of traversed nodes list = [] list.append(root) # Traverse left boundary without root # and last node temp = root.left while temp.left: list.append(temp) temp = temp.left # BFS designed to only include leaf nodes q = deque() q.append(root) while len(q) != 0: x = q.pop() if not x.left and not x.right: list.append(x) if x.right: q.append(x.right) if x.left: q.append(x.left) # Traverse right boundary without root # and last node list_r = [] temp = root.right while temp.right: list.append(temp) temp = temp.right # Reversing the order list_r = list_r[::-1] # Concatenating the two lists list += list_r # Printing the node's data from the list print (" ".join([str(i.data) for i in list])) return # Root node of the tree root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) root.right.left = Node(10) root.right.right = Node(25) boundaryTraversal(root) |
20 8 4 12 10 25 22
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Boundary Traversal of binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Boundary Level order traversal of a Binary Tree
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative diagonal traversal of binary tree
- Sideways traversal of a Complete Binary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Level order traversal of Binary Tree using Morris Traversal
- Sum of all the Boundary Nodes of a Binary Tree
- Iterative Preorder Traversal of an N-ary Tree
- Iterative Postorder Traversal of N-ary Tree
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Iterative Preorder Traversal
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Iterative Postorder traversal | Set 3
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sahajb

