LintCode: 72 中序遍历和后序遍历树构造二叉树

题目:根据中序遍历和后序遍历树构造二叉树


方法:采用递归的方法,因为二叉树的根结点在处于后序遍历的最后一个位置,在中序遍历中找出它的位置,该位置的左边为根结点的左子树,右边为右子树,然后再进行递归。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param inorder: A list of integers that inorder traversal of a tree
     * @param postorder: A list of integers that postorder traversal of a tree
     * @return: Root of a tree
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        // write your code here
        if(inorder.length<=0 || postorder.length<=0 || inorder.length!=postorder.length){
            return null;
        }
        return myBuildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }

    public TreeNode myBuildTree(int[] inorder,int instart,int inend,int[] postorder,int poststart,int postend){
        if(instart>inend)   return null;
        TreeNode root=new TreeNode(postorder[postend]);
        int position=findPosition(inorder,instart,inend,postorder[postend]);
        root.left=myBuildTree(inorder,instart,position-1,postorder,poststart,poststart+position-instart-1);
        root.right=myBuildTree(inorder,position+1,inend,postorder,poststart+position-instart,postend-1);
        return root;
    }

    public int findPosition(int[] arr,int start,int end,int key){
        int i;
        for(i=start;i<=end;i++){
            if(arr[i]==key){
                return i;
            }
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27139155/article/details/80197199
今日推荐