由preOrder和inOrder构建二叉树

Let us consider the below traversals:


Inorder sequence: D B E A F C
Preorder sequence: A B D E C F


In a Preorder sequence, leftmost element is the root of the tree. So we know ‘A’ is root for given sequences. By searching ‘A’ in Inorder sequence, we can find out all elements on left side of ‘A’ are in left subtree and elements on right are in right subtree. So we know below structure now.

                 A
               /   \
             /       \
           D B E     F C

We recursively follow above steps and get the following tree.

         A
       /   \
     /       \
    B         C
   / \        /
 /     \    /
D       E  F

Algorithm: buildTree()

  • 1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
  • 2) Create a new tree node tNode with the data as picked element.
  • 3) Find the picked element’s index in Inorder. Let the index be inIndex.
  • 4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
  • 5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
  • 6) return tNode.

 

TreeNode buildTree(char in[], char pre[], int inStr, int inEnd){
        int preIndex = 0;
        if(inStr > inEnd) return null;
         
        TreeNode tNode = new TreeNode(pre[preIndex++]);
        if(inStr == inEnd) return tNode;
         
        int inIndex = search(in, inStr, inEnd, tNode.item);
        tNode.left = buildTree(in, pre, inStr, inIndex - 1);
        tNode.right = buildTree(in, pre, inIndex + 1, inEnd);
        return tNode;
     }
      
int search(char arr[], int strt, int end, char value){
         int i;
         for(i = strt; i <= end; i++){
             if(arr[i] == value)
                 break;
         }
         return i;
     }
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值