Java | LeetCode | 106. Construct Binary Tree from Inorder and Postorder Traversal | 已知中序和后序复原树

106. Construct Binary Tree from Inorder and Postorder Traversal | 已知中序和后序复原树

class Solution {
	public TreeNode buildTree(int[] in, int[] post) {
		if(in.length==0 || post.length==0 || in.length!=post.length) return null;
		return helper(in, 0, in.length-1, post, 0, post.length-1);
	}
	private TreeNode helper(int[] in, int is, int ie, int[] post, int ps, int pe) {
		if(is>ie || ps>pe) return null;
		TreeNode root = new TreeNode(post[pe]);
		for(int i=is; i<=ie; i++) {
			if(in[i] == post[pe]) {
				root.left = helper(in, is, i-1, post, ps, ps-1+i-is);
				root.right = helper(in, i+1, ie, post, ps+i-is, pe-1);
				break;
			}
		}
		return root;
	}
}

优化:
用HashMap存储inorder的数组,时间复杂度上减少了每次循环查找post[pe]在中序中的位置

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //inorder : left root right
    //postorder : left right root
    public TreeNode buildTree(int[] in, int[] post) {
        if(in.length==0 || post.length==0 || in.length!=post.length) return null;
        HashMap<Integer, Integer> mapin = new HashMap<>();
        for(int i=0; i<in.length; i++) mapin.put(in[i],i);
		return helper(mapin, 0, in.length-1, post, 0, post.length-1);
	}
	private TreeNode helper(HashMap<Integer,Integer> mapin, int is, int ie, int[] post, int ps, int pe) {
		if(is>ie || ps>pe) return null;
		TreeNode root = new TreeNode(post[pe]);
        int i = mapin.get(post[pe]);
		root.left = helper(mapin, is, i-1, post, ps, ps-1+i-is);
		root.right = helper(mapin, i+1, ie, post, ps+i-is, pe-1);
		return root;
    }
}

你可能感兴趣的:(LeetCode)