首页 > 代码库 > Construct Binary Tree from Inorder and PreOrder Traversal

Construct Binary Tree from Inorder and PreOrder Traversal

preOrder: (root) LLL RRRR 

inOrder: LLL (root) RRRR

inOrder:  LLL RRRR (root)

 

根据preOrder/postOrder 可以知道root(一头一尾); 然后找到root在inorder中对应的位置(index)

index左边即为Left Branch(inorder), 右边是Right Branch(inorder). 确定LeftBranch && RightBranch的长度后,同样可以从PreOrder/PostOrder中获得Left Branch(preorder/postorder) && Right Branch(preorder/postorder)

 

在分别对leftBranch && right Branch 进行recursive call.

 

 

Depth-First Transversal (3 types)

preorder: root --> preorder(root.child) --> preorder(root.right)

inOrder: recursive call on leftBranch --> root --> recursive call on rightBranch

postorder: recursive call on leftBranch--> recursive call on rightBranch-->root

      =>Naming regarding the position of root !

  //pre-Condition: root is a valid treeNode

  preorder(Node){

    //boundary case: Node is a leaf 

    //recursive case: Node has child(s)

    1. do something to root

    2. if(root.left != null)

       preorder(root.left)

    3. if(root.right != null)

       preorder(root.right)

  }

Construct Binary Tree from Inorder and PreOrder Traversal