Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:虎扑认证过的aj淘宝店 编辑:程序博客网 时间:2024/05/16 06:51
/** * 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.length != postorder.length) {            return null;        }        return myBuildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);    }    private TreeNode myBuildTree(int[] inorder, int inBeg, int inEnd, int[] postorder, int postBeg, int postEnd) {        if (inBeg > inEnd) {            return null;        }        TreeNode root = new TreeNode(postorder[postEnd]);        int location = findLocation(inorder, inBeg, inEnd, postorder[postEnd]);        root.left = myBuildTree(inorder, inBeg, location - 1, postorder, postBeg, postBeg + location - inBeg - 1);        root.right = myBuildTree(inorder, location + 1, inEnd, postorder, postEnd + location - inEnd, postEnd - 1);        return root;    }    private int findLocation(int[] inorder, int begin, int end, int value) {        for (int i = begin; i <= end; i++) {            if (inorder[i] == value) {                return i;            }        }        return -1;    }  }

0 0