Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Zig-Zag traversal of a Binary Tree using Recursion
Next article icon

Iterative Boundary Traversal of Complete Binary tree

Last Updated : 05 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a complete binary tree, the task is to traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root.

Example: 

Input:

replace-each-node-in-binary-tree-with-the-sum-of-its-inorder-predecessor-and-successor

Output: 1 2 4 5 6 7 3

Input:

iterative-boundary-traversal-of-complete-binary-tree

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 below example 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.

iterative-boundary-traversal-of-complete-binary-tree
C++
// C++ program to print boundary traversal // of a complete binary tree. #include <bits/stdc++.h> using namespace std;  class Node {   public:     int data;     Node *left;     Node *right;     Node(int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // Function to print the nodes of a complete // binary tree in boundary traversal order vector<int> boundaryTraversal(Node *root) {     vector<int> ans;      if (root == nullptr)         return ans;      // If there is only 1 node print it     // and return     if (!(root->left) && !(root->right)) {         ans.push_back(root->data);         return ans;     }      ans.push_back(root->data);      // Traverse left boundary without root     // and last node     Node *l = root->left;     while (l->left) {         ans.push_back(l->data);         l = l->left;     }      // BFS designed to only include    	// leaf nodes     queue<Node *> q;     q.push(root);     while (!q.empty()) {         Node *curr = q.front();         q.pop();         if (!(curr->left) && !(curr->right)) {             ans.push_back(curr->data);         }         if (curr->left) {             q.push(curr->left);         }         if (curr->right) {             q.push(curr->right);         }     }      // Traverse right boundary without root     // and last node     vector<int> list;     Node *r = root->right;     while (r->right)     {         list.push_back(r->data);         r = r->right;     }      // Concatenate the ans and list     for (int i = list.size() - 1; i >= 0; i--) {         ans.push_back(list[i]);     }      return ans; }  int main() {      // Create a hard coded tree.     //              18     //           /     \       //          15      30     //         /  \     /  \     //       40    50  100  20      Node *root = new Node(18);     root->left = new Node(15);     root->right = new Node(30);     root->left->left = new Node(40);     root->left->right = new Node(50);     root->right->left = new Node(100);     root->right->right = new Node(20);      vector<int> ans = boundaryTraversal(root);     int n = ans.size();     for (int i = 0; i < n; i++) {         cout << ans[i] << " ";     }     return 0; } 
Java
// Java program to print boundary traversal // of a complete binary tree. import java.util.*;  class Node {     int data;     Node left;     Node right;      Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // Function to print the nodes of a complete     // binary tree in boundary traversal order     static List<Integer> boundaryTraversal(Node root) {         List<Integer> ans = new ArrayList<>();          if (root == null)             return ans;          // If there is only 1 node print it         // and return         if (root.left == null && root.right == null) {             ans.add(root.data);             return ans;         }          ans.add(root.data);          // Traverse left boundary without root         // and last node         Node l = root.left;         while (l != null && l.left != null) {             ans.add(l.data);             l = l.left;         }          // BFS designed to only include leaf nodes         Queue<Node> q = new LinkedList<>();         q.add(root);         while (!q.isEmpty()) {             Node curr = q.poll();             if (curr.left == null && curr.right == null) {                 ans.add(curr.data);             }             if (curr.left != null) {                 q.add(curr.left);             }             if (curr.right != null) {                 q.add(curr.right);             }         }          // Traverse right boundary without root         // and last node         List<Integer> list = new ArrayList<>();         Node r = root.right;         while (r != null && r.right != null) {             list.add(r.data);             r = r.right;         }          // Concatenate the ans and list         for (int i = list.size() - 1; i >= 0; i--) {             ans.add(list.get(i));         }          return ans;     }      public static void main(String[] args) {          // Create a hard coded tree.         //              18         //           /     \           //          15      30         //         /  \     /  \         //       40    50  100  20         Node root = new Node(18);         root.left = new Node(15);         root.right = new Node(30);         root.left.left = new Node(40);         root.left.right = new Node(50);         root.right.left = new Node(100);         root.right.right = new Node(20);          List<Integer> ans = boundaryTraversal(root);         for (int value : ans) {             System.out.print(value + " ");         }     } } 
Python
# Python program to print boundary traversal # of a complete binary tree.  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Function to print the nodes of a complete # binary tree in boundary traversal order  def boundary_traversal(root):     ans = []      if root is None:         return ans      # If there is only 1 node print it     # and return     if root.left is None and root.right is None:         ans.append(root.data)         return ans      ans.append(root.data)      # Traverse left boundary without root     # and last node     l = root.left     while l and l.left:         ans.append(l.data)         l = l.left      # BFS designed to only include leaf nodes     from collections import deque     q = deque([root])     while q:         curr = q.popleft()         if curr.left is None and curr.right is None:             ans.append(curr.data)         if curr.left:             q.append(curr.left)         if curr.right:             q.append(curr.right)      # Traverse right boundary without root     # and last node     list = []     r = root.right     while r and r.right:         list.append(r.data)         r = r.right      # Concatenate the ans and list     ans.extend(reversed(list))      return ans  if __name__ == "__main__":      # Create a hard coded tree.     #              18     #           /     \     #          15      30     #         /  \     /  \     #       40    50  100  20     root = Node(18)     root.left = Node(15)     root.right = Node(30)     root.left.left = Node(40)     root.left.right = Node(50)     root.right.left = Node(100)     root.right.right = Node(20)      ans = boundary_traversal(root)     for value in ans:         print(value, end=" ") 
C#
// C# program to print boundary traversal // of a complete binary tree.  using System; using System.Collections.Generic;  class Node {     public int data;     public Node left;     public Node right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // Function to print the nodes of a complete     // binary tree in boundary traversal order     static List<int> boundaryTraversal(Node root) {         List<int> ans = new List<int>();          if (root == null)             return ans;          // If there is only 1 node print it         // and return         if (root.left == null && root.right == null) {             ans.Add(root.data);             return ans;         }          ans.Add(root.data);          // Traverse left boundary without root         // and last node         Node l = root.left;         while (l != null && l.left != null) {             ans.Add(l.data);             l = l.left;         }          // BFS designed to only include leaf nodes         Queue<Node> q = new Queue<Node>();         q.Enqueue(root);         while (q.Count > 0) {             Node curr = q.Dequeue();             if (curr.left == null && curr.right == null) {                 ans.Add(curr.data);             }             if (curr.left != null) {                 q.Enqueue(curr.left);             }             if (curr.right != null) {                 q.Enqueue(curr.right);             }         }          // Traverse right boundary without root         // and last node         List<int> list = new List<int>();         Node r = root.right;         while (r != null && r.right != null) {             list.Add(r.data);             r = r.right;         }          // Concatenate the ans and list         for (int i = list.Count - 1; i >= 0; i--) {             ans.Add(list[i]);         }          return ans;     }      static void Main(string[] args) {          // Create a hard coded tree.         //              18         //           /     \           //          15      30         //         /  \     /  \         //       40    50  100  20         Node root = new Node(18);         root.left = new Node(15);         root.right = new Node(30);         root.left.left = new Node(40);         root.left.right = new Node(50);         root.right.left = new Node(100);         root.right.right = new Node(20);          List<int> ans = boundaryTraversal(root);         foreach(var value in ans) {             Console.Write(value + " ");         }     } } 
JavaScript
// JavaScript program to print boundary traversal // of a complete binary tree.  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Function to print the nodes of a complete // binary tree in boundary traversal order function boundaryTraversal(root) {     let ans = [];      if (root === null)         return ans;      // If there is only 1 node print it     // and return     if (root.left === null && root.right === null) {         ans.push(root.data);         return ans;     }      ans.push(root.data);      // Traverse left boundary without root     // and last node     let l = root.left;     while (l && l.left) {         ans.push(l.data);         l = l.left;     }      // BFS designed to only include leaf nodes     let queue = [];     queue.push(root);     while (queue.length > 0) {         let curr = queue.shift();         if (curr.left === null && curr.right === null) {             ans.push(curr.data);         }         if (curr.left) {             queue.push(curr.left);         }         if (curr.right) {             queue.push(curr.right);         }     }      // Traverse right boundary without root     // and last node     let list = [];     let r = root.right;     while (r && r.right) {         list.push(r.data);         r = r.right;     }      // Concatenate the ans and list     for (let i = list.length - 1; i >= 0; i--) {         ans.push(list[i]);     }      return ans; }  // Create a hard coded tree. //              18 //           /     \   //          15      30 //         /  \     /  \ //       40    50  100  20 let root = new Node(18); root.left = new Node(15); root.right = new Node(30); root.left.left = new Node(40); root.left.right = new Node(50); root.right.left = new Node(100); root.right.right = new Node(20);  let ans = boundaryTraversal(root); for (let value of ans) {         console.log(value + " ");     } 

Output
18 15 40 50 100 20 30 

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)



Next Article
Zig-Zag traversal of a Binary Tree using Recursion

S

sahajb
Improve
Article Tags :
  • C++ Programs
  • DSA
  • Python Programs
  • Tree
Practice Tags :
  • Tree

Similar Reads

  • Inorder Tree Traversal of Binary Tree in C++
    A binary tree is a non-linear hierarchical data structure in which each node has at most two children known as the left child and the right child. As the binary tree has non-linear structure it can be traversed in multiple ways one such way is in-order traversal which is a depth first (DFS) traversa
    4 min read
  • Clockwise Spiral Traversal of Binary Tree | Set - 2
    Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output :1 9 8 7 2 3 6 5 4 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output :20 14 10 8 22 25 4 3 5 We have already discussed Clock
    11 min read
  • Flatten Binary Tree in order of Zig Zag traversal
    Given a Binary Tree, the task is to flatten it in order of ZigZag traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 2 5 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this
    7 min read
  • Zig-Zag traversal of a Binary Tree using Recursion
    Given a binary tree, the task is to find the zigzag level order traversal of the tree. In zig zag traversal starting from the first level go from left to right for odd-numbered levels and right to left for even-numbered levels. Approach: The zigzag traversal of a binary tree involves traversing the
    11 min read
  • Reverse Anti Clockwise Spiral Traversal of a Binary Tree
    Given a binary tree, the task is to print the nodes of the tree in a reverse anti-clockwise spiral manner. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 7 8 9 1 4 5 6 3 2 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output : 10 14 20 5 3 4 25 22 8 Approach: The idea is to use two va
    11 min read
  • Deletion of a given node K in a Binary Tree using Level Order Traversal
    Given a binary tree and a node K, the task is to delete the node K from it by making sure that tree shrinks from the bottom (i.e. the deleted node is replaced by bottom-most and rightmost node) using Level Order Traversal. Examples: Input: K = 8, Tree = Output: Explanation: Please Refer below for ex
    13 min read
  • Connect all nodes to their Left Neighbors in a Binary Tree
    Given a Binary Tree, where each node contains an extra empty pointer initially null. The task is to connect all nodes of the binary tree to their left neighbor at the same level using this extra pointer.Examples: Input : A / \ B C / \ \ D E F Output : NULL<--A / \ NULL<--B<--C / \ \ NULL
    10 min read
  • Flatten a binary tree into linked list
    Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder. Examples: Input : 1 / \ 2 5 / \ \ 3 4 6Output : 1 \ 2 \ 3 \ 4 \ 5 \ 6Input : 1 / \ 3 4
    15+ min read
  • Print nodes in top view of Binary Tree | Set 2
    Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
    14 min read
  • Binary Search Tree in C++
    A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn't follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and el
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences