For the binary tree, here I do not do too much to explain, if you do not understand, please refer to the link click to open the link
1, the definition of this binary tree:
struct binarytreenode { Binarytreenode<t> *_left; binarytreenode<t> *_right; t _data; public: binarytreenode (const t& x) :_left (NULL) , _right (NULL) , _data (x) {} }; template<class T> class Binarytree { typedef binarytreenode <t> node; &nbSp;public: binarytree () :_root (NULL) {} }
2. Reconstruction of binary tree by pre-sequence traversal and middle sequence traversal
thought:
1, Binary tree in the pre-sequence traversal, the first element is always the value of the root node,
2, the middle sequence traversal, the value of the node of the Zuozi is located at the root node worth left,
3. The value of the node of the right subtree is at the root node worth the right.
4, if the pre-sequence traversal is empty or the middle sequence traversal is empty or the number of nodes is less than or equal to 0, returns null;
5, the root node is created, the first data of the pre-sequence traversal is the data of the root node, and the root node location is found in the middle sequence traversal .
6, we know the Saozi of the right sub-tree of the first order and the sequence of sequential traversal, reconstruction of the subtree.
recursive implementation:
Node * rebuildbinarytree (T* prevorder, t* inorder, int num) { if (prevorder == null | | inorder == null | | num <= 0) { return NULL; } node* root = new node (PrevOrder[0]); // the first data for a pre-order traversal is the root node data //sequence traversal, root node left is left dial hand tree, right is right subtree int rootposition = -1; for (int i = 0; i < num; i++) { if (inorder[i] == root- >_data) { rootposition = i; } } if (rootposition == -1) return null; //Rebuilding Zuozi (root node) recursion int LeftNum = rootposition; int *prevorderleft = prevorder + 1; // The second of the first order is the left subtree of the root node int *inorderleft The first in the = inorder; //sequence is its left subtree. root->_Left = Rebuildbinarytree (Prevorderleft, inorderleft, leftnum); //reconstruction right subtree (root node) recursion int rightnum = num - leftnum - 1; int *prevorderright = prevorder + 1 + leftnum; int *inorderright = InOrder + LeftNum + 1; root->_right = rebuildbinarytree (prevorderright, inorderright, Rightnum); return root; }
This article is from the "Potato _" blog, please be sure to keep this source http://10738432.blog.51cto.com/10728432/1790682
Reconstruction of binary tree by pre-sequence traversal and middle sequence traversal