`

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.

用后序遍历序列来确定根节点的位置,然后在中序遍历中确定左右子树,递归完成树的构造。代码如下:
/**
 * Definition for a binary tree node.
 * 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 == 0 || postorder.length == 0) 
            return null;
        TreeNode root = new TreeNode(postorder[postorder.length - 1]);
        int i;
        for(i = 0; i < inorder.length; i++) {
            if(inorder[i] == postorder[postorder.length-1])
                break;
        }
        int[] lp = Arrays.copyOfRange(postorder, 0, i);
        int[] li = Arrays.copyOfRange(inorder, 0, i);
        int[] rp = Arrays.copyOfRange(postorder, i, postorder.length - 1);
        int[] ri = Arrays.copyOfRange(inorder, i + 1, inorder.length);
        root.left = buildTree(li, lp);
        root.right = buildTree(ri, rp);
        return root;
    }
}


0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics