Reconstructing binary tree based on pre-order and middle sequence traversal

Source: Internet
Author: User

1  Public classReconstructbinarytree {2      Public Static voidMain (string[] args) {3         NewReconstructbinarytree (). Reconstructbinarytree (New int[] {1, 2, 4,47, 3, 5, 6, 8},New int[] {4, 7, 2, 1, 5, 3, 8, 6 });5     }6 7      PublicTreeNode Reconstructbinarytree (int[] Pre,int[] in) {8         returnReconstructbinarytree (pre, 0, Pre.length-1, in, 0,9In.length-1);Ten     } One  A      PublicTreeNode Reconstructbinarytree (int[] Pre,intStartpre,intEndpre, -             int[] in,intStartin,intEndin) { -  the         if(Startpre > Endpre | | startin >Endin) -             return NULL; -  -TreeNode root =NewTreeNode (Pre[startpre]);//Constructing Roots +          for(inti = Startin; I <= Endin; i++) { -             //finding roots in the middle sequence traversal +             if(In[i] = =Pre[startpre]) { A  atRoot.left = Reconstructbinarytree (pre, Startpre + 1, I --Startin + Startpre, in, Startin, i-1); -Root.right = Reconstructbinarytree (pre, I-startin +Startpre -+ 1, Endpre, in, i + 1, Endin); -                  Break; -             } in         } -  to         returnRoot; +     } - } the  * classTreeNode { $     intVal;Panax Notoginseng TreeNode left; - TreeNode right; the  +TreeNode (intx) { Aval =x; the     } +}

Pre-sequence traversal: 12473568

Middle Sequence Traversal: 47215386

Refactoring process: 1. The first value in a pre-order traversal is the root

2. The location of the root in the middle sequence traversal, the left side is the Zuozi of the middle order traversal result (472), right is the right subtree of the middle sequence traversal results (5386)

3. In the pre-sequence traversal, the pre-order traversal result of the Zuozi is (247), and the first-order traversal result of the right subtree is (3568)

4.2 is the root of the Zuozi, and 3 is the root of the right subtree, repeating the above operation

Reconstructing binary tree based on pre-order and middle sequence traversal

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.