Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Spiral level order traversal of a binary tree

Автор: IDeserve

Загружено: 2016-02-28

Просмотров: 6525

Описание:

Given a binary tree, write a program to print nodes of the tree in a spiral order.

The idea to traverse the given binary tree in spiral order is similar to level order traversal.

In level order traversal we make use of a single queue while in spiral order traversal we need use two stacks. First stack('stackEven') is used to traverse the nodes at even level and second stack('stackOdd') is used to traverse the nodes at odd level. Nodes at even level are stored in 'stackEven' and are pushed in it from left to right order whereas nodes at odd level are stored in 'stackOdd' and are pushed in it from right to left order.

Algorithm:
1. Push root node into the 'stackEven'. Set boolean 'evenLevel' to true. This boolean variable is used to indicate if the current level being visited is even level or odd level.

2. Now if 'evenLevel' is set to true repeat steps 2a to 2c until 'stackEven' is not empty.
2a. Pop the node from 'stackEven'. Let popped node be 'currentNode'. Print the value of 'currentNode'.
2b. If the right child of 'currentNode' is not null, push it into the 'stackOdd'.
2c. If the left child of 'currentNode' is not null, push it into the 'stackOdd'.
Notice that currentNode's right child is pushed first and then its left child is pushed.

3. If 'evenLevel' is not set to true then repeat steps 3a to 3c until 'stackOdd' is not empty.
3a. Pop the node from 'stackOdd'. Let popped node be 'currentNode'. Print the value of 'currentNode'.
3b. If the left child of 'currentNode' is not null, push it into the 'stackEven'.
3c. If the right child of 'currentNode' is not null, push it into the 'stackEven'.
Notice that currentNode's left child is pushed first and then its right child is pushed.

4. If 'evenLevel' is true set it to false and if it is false set it to true. This is because the next level visited would be odd if current level is even and vice versa.


5. Repeat steps 2-4 until both 'stackEven' and 'stackOdd' are not empty.

The time complexity of this algorithm is O(n) and extra space used is also O(n). Please add comments below in case you have any queries/feedback.

Code and Algorithm Visualization:
http://www.ideserve.co.in/learn/spira...

Website: http://www.ideserve.co.in

Facebook:   / ideserve.co.in  

Spiral level order traversal of a binary tree

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Check if Binary Tree is Symmetric or Not

Check if Binary Tree is Symmetric or Not

Понимание B-деревьев: структура данных, лежащая в основе современных баз данных

Понимание B-деревьев: структура данных, лежащая в основе современных баз данных

Serialize and Deserialize a Binary Tree

Serialize and Deserialize a Binary Tree

Spiral Matrix - Microsoft Interview Question - Leetcode 54

Spiral Matrix - Microsoft Interview Question - Leetcode 54

L24. Right/Left View of Binary Tree | C++ | Java

L24. Right/Left View of Binary Tree | C++ | Java

Serialize and Deserialize a Binary Search Tree in O(n) time

Serialize and Deserialize a Binary Search Tree in O(n) time

Фронт. Усталость и отрешенность

Фронт. Усталость и отрешенность

Свёрточные нейронные сети | CNN | Ядро | Шаг | Заполнение | Объединение | Сглаживание | Формула

Свёрточные нейронные сети | CNN | Ядро | Шаг | Заполнение | Объединение | Сглаживание | Формула

Алгоритмы и структуры данных за 15 минут! Вместо 4 лет универа

Алгоритмы и структуры данных за 15 минут! Вместо 4 лет универа

БЕЛЫЕ СПИСКИ: какой VPN-протокол справится? Сравниваю все

БЕЛЫЕ СПИСКИ: какой VPN-протокол справится? Сравниваю все

5.28 B-Tree Deletion in Data Structures | DSA Tutorials

5.28 B-Tree Deletion in Data Structures | DSA Tutorials

Но что такое нейронная сеть? | Глава 1. Глубокое обучение

Но что такое нейронная сеть? | Глава 1. Глубокое обучение

1.11 Анализ лучшего, худшего и среднего случая

1.11 Анализ лучшего, худшего и среднего случая

Теорема Байеса, геометрия изменения убеждений

Теорема Байеса, геометрия изменения убеждений

Height of a Binary Tree / Maximum depth of a binary tree Algorithm [REVISITED]

Height of a Binary Tree / Maximum depth of a binary tree Algorithm [REVISITED]

Serialize and Deserialize a Binary Search Tree

Serialize and Deserialize a Binary Search Tree

Как производятся микрочипы? 🖥️🛠️ Этапы производства процессоров

Как производятся микрочипы? 🖥️🛠️ Этапы производства процессоров

Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python

Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python

L12. Iterative Postorder Traversal using 1 Stack | C++ | Java | Binary Trees

L12. Iterative Postorder Traversal using 1 Stack | C++ | Java | Binary Trees

Управление рукой робота с помощью необычного алгоритма

Управление рукой робота с помощью необычного алгоритма

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]