码迷,mamicode.com
首页 > 其他好文 > 详细

Construct Binary Tree from Inorder and PreOrder Traversal

时间:2014-12-30 14:50:20      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/jinagyuanhk/p/4193431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!