Writes an algorithm that traverses a binary tree in a hierarchical order (same layer from left to right).
#include "stdafx.h" #include <iostream> #include <vector> using namespace std;struct binode{int ele; binode* Lnode; Binode* Rnode;}; vector<vector<int>>aa; Binode*p; Binode*root;void findparent (Binode*node, binode*parent) {if (parent = = NULL) return;if (Parent->lnode = = Node | | Parent->rnode = = node) {p = parent; return;} Findparent (node, parent->lnode); findparent (node, parent->rnode);} int Depth_of_node (binode*node) {int k = 0;if (node = = root) return 0; Binode*n = Node;while (n! = root) {Findparent (n, root); n = p;k++;} return k;} void Preordertraverse (Binode*node) {if (node = = NULL) Return;int d = depth_of_node (node), if (D + 1 > aa.size ()) {Vector< ; Int>a;a.push_back (Node->ele); Aa.push_back (a);} Else{vector<int>a=aa[d];a.push_back (Node->ele); aa[d] = A;} if (Node->lnode! = null) preordertraverse (Node->lnode); if (node->rnode! = null) Preordertraverse (node-> Rnode);} Binode*create_tree () {Binode * root = new Binode; Binode*node1 = new Binode; BiNODe*node2 = new Binode; Binode*node3 = new Binode; Binode*node4 = new Binode; BINODE*NODE5 = new Binode; Binode*node6 = new Binode; Binode*node7 = new Binode; Binode*node8 = new Binode; Binode*node9 = new Binode; Binode*node10 = new Binode; Binode*node11 = new Binode;root->ele = 0;node1->ele = 1;node2->ele = 2;node3->ele = 3;node4->ele = 4;node5- >ele = 5;node6->ele = 6;node7->ele = 7;node8->ele = 8;node9->ele = 9;node10->ele = 10;node11->ele = 1 1;root->lnode = Node1;root->rnode = Node2;node1->lnode = Node3;node1->rnode = Node4;node2->lnode = Node7; Node2->rnode = Node8;node3->lnode = Node5;node3->rnode = Node11;node4->lnode = Node10;node4->rnode = NULL ; node5->lnode = Node6;node5->rnode = Null;node6->lnode = Null;node6->rnode = NULL;node7->lnode = Node9; Node7->rnode = Null;node8->lnode = Null;node8->rnode = Null;node9->lnode = NULL;node9->rnode = NULL; Node10->lnode = Null;node10->rnode = Null;node11->lnode = Null;node11->rnode = Null;//binode*node12 = new Binode; Node12->ele = 12; Node12->lnode = NULL; Node12->rnode = NULL; Node6->lnode = Node11; return root;} int _tmain (int argc, _tchar* argv[]) {root = Create_tree (); Preordertraverse (root); system ("pause"); return 0;}
Sequential traversal of the tree, the same depth of the node access is not sequential, but it satisfies the order from left to right, just the same depth of the node in turn to an array.
In the main function of the system ("pause") This sentence set breakpoints, the global variable AA added monitoring, run to the system when the sentence paused to observe the data stored in AA, the result is correct.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Traverse a binary tree by hierarchy