LeetCode 46 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.

分析:

后序遍历,最后一个元素就是root,因为没有重复元素,遍历中序数组,找到root位置,把中序分成两半,再根据中序长度,把后序分成两半,递归得建立二叉树。

/**
 * 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) {
        if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0)
            return null;
        int length = inorder.length;
        TreeNode root = buildTree(inorder, 0, length-1, postorder, 0, length-1);
        return root;
    }
    
    public TreeNode buildTree(int[] inorder, int iStart, int iEnd, int[] postorder, int pStart, int pEnd){
        if(iStart > iEnd || pStart > pEnd)
            return null;
        
        TreeNode root = new TreeNode(postorder[pEnd]);
        int index = 0;
        while(inorder[iStart + index] != root.val)
            index++;
        root.left = buildTree(inorder, iStart, iStart+index-1, postorder, pStart, pStart+index-1);
        root.right = buildTree(inorder, iStart+index+1, iEnd, postorder, pStart+index, pEnd-1);
        
        return root;
    }
}


你可能感兴趣的:(LeetCode,递归,构造二叉树,中序后序)