[leet code] Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

=================

A scary problem at the very beginning.  What we can do is to try an example for both inorder and postorder traversal, and find out the pattern between these two arrays.

in-order:  A,B,C,D,E,F,G,H,I

File:Sorted binary tree inorder.svg


post-order: A, C, E, D, B, H, I, G, F

File:Sorted binary tree postorder.svg

From which we can found that the right most element in post-order array is the root node, then use this element as the split point, we can split the in-order array into left part and right part.  Tree nodes in left part are belong to current root node's left sub-tree, while the nodes in right part are belong to current root node's right sub-tree.

Accordingly, we can use recursive approach to further build current node's left sub-tree and right sub-tree.

Note that the position of split point for in order array (inside the current array) and post order array (always at the end of the current array) are different.  Therefore, we need to specify left/right bond of sub-array for in order array and post order array respectively.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
    }
    
    public TreeNode helper(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight){
        if(inLeft>inRight||postLeft>postRight) return null;
        
        TreeNode curr = new TreeNode(postorder[postRight]);
        int splitPoint = 0;
        for(int i=inLeft; i<=inRight; i++){
            if(inorder[i] == curr.val){
                splitPoint = i;
                break;
            }
        }
        
        curr.left = helper(inorder, inLeft, splitPoint-1, postorder, postLeft, postLeft+(splitPoint-inLeft-1));
        // splitPoint-inLeft-1 is the length of subarray
        curr.right = helper(inorder, splitPoint+1, inRight, postorder, postLeft+(splitPoint-inLeft), postRight-1);
        
        return curr;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值