c++ - What is logic to construct a binary tree? -
i have while loop continuously takes integers until -1 entered. elements must inserted binary tree (not bst). if bst, have condition insert new node. how can construct binary tree?
i mean if nodes 1,2,3,4,5,6..., 1 root, 2 , 3 left , right children of node 1, 4 , 5 left , right children of node 2, , 6 left child of node 3, this:
if(root==null) root= newnode; else{ if (root->left==null) root->left= insert(root->left,element); else root->right= insert(root->right,element); } return root;
how create tree this?
the algorithm outlined whozcraig in comment can realized code:
/* create binary tree nodes presented in bfs order */ #include <cassert> #include <iostream> #include <vector> #include <iomanip> using std::vector; using std::cout; using std::cin; using std::ostream; using std::setw; struct node { int data; node *left; node *right; node(int n) : data(n), left(0), right(0) { } }; void print_bt(const node *root); int main() { vector<node> v; int n; // read data eof or negative value while (cin >> n && n >= 0) v.push_back(node(n)); // create binary tree (size_t = 0; < v.size()/2; i++) { assert(2*i+1 < v.size()); v[i].left = &v[2*i+1]; if (2*i+2 < v.size()) v[i].right = &v[2*i+2]; } // print binary tree print_bt(&v[0]); return 0; } // print_bt() presents data if mentally rotate // output through 90º clockwise (so root @ top), // left child appears on left , right on right. reversing // order of left/right leaves confusing. void print_bt(const node *root) { static int level = 0; if (root != nullptr) { level++; print_bt(root->right); cout << setw(4*level) << root->data << '\n'; print_bt(root->left); level--; } }
for example, given numbers 1 6 input, produces:
3 6 1 5 2 4
and given numbers 1 15 input, produces:
15 7 14 3 13 6 12 1 11 5 10 2 9 4 8
it helps if visualize tree rotated 90º clockwise, 1
@ top.
Comments
Post a Comment