Construct Binary Tree from Inorder and Postorder Traversal

/**
 * 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;
    }  
}

阅读更多
文章标签: Array DFS Tree
个人分类: Leetcode 刷题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭