1.题目描述:
给定两个整数数组preorder和inorder,其中preorder是二叉树的先序遍历,inorder是同一棵树的中序遍历,请构造二叉树并返回其根节点。
2.递归:
具体思路详见leetcode106. 从中序与后序遍历序列构造二叉树类似,只是找到前序遍历的首位元素来对中序遍历的数组进行分割,直接上代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(preorder, 0, preorder.length, inorder, 0, inorder.length);
}
public TreeNode helper(int[] preorder, int preleft, int preright, int[] inorder, int inleft, int inright) {
if (preleft == preright || inleft == inright) return null;
int first = preorder[preleft];
int index = 0;
for (int i = inleft; i < inright; i++) {
if (inorder[i] == first) index = i;
}
TreeNode root = new TreeNode(first);
root.left = helper(preorder, preleft + 1, preleft + (index - inleft) + 1, inorder, inleft, index);
root.right = helper(preorder, preleft + (index - inleft) + 1, preright, inorder, index + 1, inright);
return root;
}
}
3.迭代。。。待更新