LeetCode889. 根据前序和后序遍历构造二叉树

题目来源:

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/

题目描述:

LeetCode889. 根据前序和后序遍历构造二叉树_第1张图片

代码如下:

class Solution {
	public TreeNode constructFromPrePost(int[] pre, int[] post) {
		return helper(pre, post, 0, pre.length - 1, 0, post.length - 1);
	}

	public TreeNode helper(int[] pre, int[] post, int prestart, int preend, int poststart, int postend) {
		if (prestart > preend || poststart > postend)
			return null;
		TreeNode node = new TreeNode(pre[prestart]);
		if (prestart + 1 > preend)
			return node;
		int val = pre[prestart + 1], index = poststart;
		for (; index < postend && post[index] != val; index++);
		int length = index - poststart;
		node.left = helper(pre, post, prestart + 1, prestart + length + 1, poststart, index);
		node.right = helper(pre, post, prestart + length + 2, preend, index + 1, postend - 1);
		return node;
	}
}

 

 

你可能感兴趣的:(LeetCode)