java 106.从Inorder和Postorder Traversal构建二叉树(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 106.从Inorder和Postorder Traversal构建二叉树(#)。java相关的知识,希望对你有一定的参考价值。

/**
 * 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) {
        int[] ps = new int[] {postorder.length - 1};
        return helper(inorder, postorder, 0, inorder.length - 1, ps);
    }
    
    private TreeNode helper(int[] in, int[] pos, int is, int ie, int[] ps) {
        if (is > ie) return null;
        TreeNode root = new TreeNode(pos[ps[0]--]);
        int i = 0;
        for (i = ie; i >= is; i--) if (in[i] == root.val) break;
        root.right = helper(in, pos, i + 1, ie, ps);
        root.left = helper(in, pos, is, i - 1, ps);
        return root;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private TreeNode helper(int[] inorder, int[] postorder, int rootIdx, int start, int end) {
        if (rootIdx > inorder.length || start > end) return null;
        TreeNode root = new TreeNode (postorder[rootIdx]);
        int inIdx = 0;
        for (int i = start ; i <= end; i++) {
            if (inorder[i] == root.val) {
                inIdx = i;
            }
        }
        root.left = helper(inorder, postorder, rootIdx - (end - inIdx) - 1, start, inIdx - 1);
        root.right = helper(inorder, postorder, rootIdx - 1, inIdx + 1, end);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return helper(inorder, postorder,postorder.length - 1, 0, postorder.length - 1);
    }
}

以上是关于java 106.从Inorder和Postorder Traversal构建二叉树(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 106.从Inorder和Postorder Traversal构建二叉树(#)。java

java 106.从Inorder和Postorder Traversal构建二叉树(#)。java

java 106.从Inorder和Postorder Traversal构建二叉树(#)。java

java 106.从Inorder和Postorder Traversal构建二叉树(#)。java

java 106.从Inorder和Postorder Traversal构建二叉树(#)。java

leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal----- java