Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
tree
#include<iostream> #include<queue> #include<set> using namespace std; struct node { int value; node *left, *right; node() { left = right = NULL; } }; node* insertNode(node* n, int value) { if(n==NULL) { node* new_node = new node(); new_node->value = value; return new_node; } else if(value==n->value) return n; else if(value < n->value) { n->left = insertNode(n->left, value); return n; } else { n->right = insertNode(n->right, value); return n; } } struct node_level { node* n; int level; node_level(node* t, int l):n(t), level(l){} }; void levelOrder(node *root) { queue<node_level> q; set<int> levels; node_level r(root, 0); q.push(r); while(!q.empty()) { r = q.front(); if(levels.find(r.level) != levels.end()) { cout << "," << r.n->value; } else { levels.insert(r.level); cout << endl << "Level " << r.level << ": " << r.n->value; } q.pop(); if(r.n->left) { node_level t(r.n->left, r.level+1); q.push(t); } if(r.n->right) { node_level t(r.n->right, r.level+1); q.push(t); } } cout << endl; } void inorder(node *n) { if(n->left) inorder(n->left); cout << n->value << endl; if(n->right) inorder(n->right); } void preorder(node *n) { cout << n->value << endl; if(n->left) inorder(n->left); if(n->right) inorder(n->right); } bool exists(node *n, int v) { if(n==NULL) return false; if(n->value==v) return true; else if(v < n->value) return exists(n->left, v); else return exists(n->right, v); } int height(node *n) { if(n==NULL) return 0; if(n->left==NULL && n->right==NULL) return 1; else return max(height(n->left), height(n->right))+1; } bool isBalanced(node *n) { } int main() { node *tree1; tree1 = insertNode(NULL, 5); insertNode(tree1, 1); insertNode(tree1, 3); insertNode(tree1, 2); insertNode(tree1, 6); insertNode(tree1, 12); insertNode(tree1, 13); insertNode(tree1, 14); cout << endl << "Levelorder:::" << endl; levelOrder(tree1); cout << endl << "Inorder:::" << endl; inorder(tree1); cout << endl << "Preorder:::" << endl; preorder(tree1); int v = 7; cout << endl << "Checking if " << v << "exists..." << endl; exists(tree1, 7)?cout << "exists": cout << "does not exist"; cout << endl << "Height:::" << height(tree1) << endl; cout << endl << "Is tree balanced??" << isBalanced(tree1) << endl; }
run
|
edit
|
history
|
help
0
Polimorfizm :)
Variadic Functor Example
Metodos mejorado
c++_array_size
Translating binary to decimal numbers
DayTempEnum
Sort row sorted matrix
Proga1
顺序表的实现——静态分配
Lowest common ancestor in binary tree