输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ 9 20
/ 15 7
由此可得:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return recursionBuildTree(preorder,inorder,0,preorder.length - 1);
}
int num = 0;
public TreeNode recursionBuildTree(int[] preorder, int[] inorder, int l, int r){
if (l > r)
return null;
TreeNode root = new TreeNode(preorder[num++]);
if (l == r)
return root;
int i = l;
for (; i <= r; i++) {
if (inorder[i] == root.val)
break;
}
root.left = recursionBuildTree(preorder,inorder, l, i-1);
root.right = recursionBuildTree(preorder,inorder, i+1, r);
return root;
}
public static void main(String[] args) {
int []preorder = {3,9,20,15,7};
int []inorder = {9,3,15,20,7};
TreeNode root = new Solution().buildTree(preorder,inorder);
System.out.println(root.val);
System.out.println(root.left.val + "\t" + root.right.val);
System.out.println(root.right.left.val + "\t" + root.right.right.val);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
原文:https://www.cnblogs.com/chengejie/p/14854008.html