The binary tree can only be re-built in the forward or backward order. It is not possible to re-build the binary tree in the forward or backward order, because the left and right Subtrees need to be divided in the middle order.
/*** Source code name: constructbt. java * Date: 2014-09-05 * program function: rebuilding a binary tree (in the forward order) * copyright: [email protected] * a2bgeek */public class constructbt {class node <t> {T mvalue; node <t> mleft; node <t> mright; Public node (T value, node <t> left, node <t> right) {mvalue = value; mleft = left; mright = right ;}} public node <character> buildbt (string pre, string mid) {node <character> root = NULL; string lpre, rpre, lmid, rmid; int Pos = 0; if (Pre. length () = 0 | mid. length () = 0) {return NULL;} else {root = new node <character> (pre. charat (0), null, null); While (MID. charat (POS )! = Root. mvalue) {pos ++;} // recursive leftlpre = pre. substring (1, POS + 1); lmid = mid. substring (0, POS); root. mleft = buildbt (lpre, lmid); // recursive rightrpre = pre. substring (Pos + 1, pre. length (); rmid = mid. substring (Pos + 1, mid. length (); root. mright = buildbt (rpre, rmid);} return root;} public void postiterate (node <character> root) {If (root = NULL) {return ;} else {postiterate (root. mleft); postiterate (root. mright); system. out. print (root. mvalue + "") ;}} public static void main (string [] ARGs) {constructbt bt = new constructbt (); node <character> root = BT. buildbt ("12473568", "47215386"); BT. postiterate (Root );}}
[Data structure and algorithm] rebuilding a binary tree