[Data structure and algorithm] rebuilding a binary tree

Source: Internet
Author: User

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.

    • Code Implementation

/*** 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.