关闭

Construct Binary Tree from Inorder and Postorder Traversal

标签: ArrayDFSTree
178人阅读 评论(0) 收藏 举报
分类:
/**
 * 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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27664次
    • 积分:2364
    • 等级:
    • 排名:第16342名
    • 原创:214篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条