Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
BInTree Traversal
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//All tree traversal #include <iostream> #include <queue> #include <string> #include <list> using namespace std; struct node { int data; node* left; node* right; node(int d): data(d), left(NULL), right(NULL) {} node(int d, node* l, node* r): data(d), left(l), right(r) {} }; void recursivePreorder(node* root) { if (!root) return; cout << root->data << " "; recursivePreorder(root->left); recursivePreorder(root->right); } void iterativeLevelorder(node* root) { queue<node*> *cur = new queue<node*>(); queue<node*> *next = new queue<node*>(); cur->push(root); while (!cur->empty()) { node* n = cur->front(); cur->pop(); cout << n->data << " "; if (n->left) next->push(n->left); if (n->right) next->push(n->right); if (cur->empty()){ swap(cur, next); cout << endl; } } } void iterativeZigZagorder(node* root) { list<node*> *cur = new list<node*>(); list<node*> *next = new list<node*>(); cur->push_back(root); bool b = false; while (!cur->empty()) { node* n = cur->back(); cur->pop_back(); cout << n->data << " "; if (b) { if (n->left) next->push_back(n->left); if (n->right) next->push_back(n->right); } else { if (n->right) next->push_back(n->right); if (n->left) next->push_back(n->left); } if (cur->empty()){ swap(cur, next); b = !b; cout << endl; } } } // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 // / \ // 8 9 int main() { node *h = new node(9, NULL, NULL); node *j = new node(8, NULL, NULL); node *g = new node(7, NULL, NULL); node *f = new node(6, j, h); node *e = new node(5, NULL, NULL); node *d = new node(4, NULL, NULL); node *c = new node(3, f, g); node *b = new node(2, d, e); node *a = new node(1, b, c); //recursivePreorder(a); //iterativeLevelorder(a); iterativeZigZagorder(a); }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.58 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0.73 sec
fork mode
|
history
|
discussion
1 2 3 7 6 5 4 8 9