题目
根据前序遍历和中序遍历构造二叉树.
注意:这里默认二叉树中的值都是唯一的。
样例
给出前序遍历:int[] preOrder = { 6, 10, 4, 3, 1, 0, 7, 12 };
中序遍历:int[] inOrder = { 4, 10, 3, 1, 6, 12, 7, 0 };
返回如下的树:
1 | _______6______ |
分析
首先还是对数组进行判断,如果前序遍历数组为null或后续遍历数组为null,则return null;前序遍历的第一个结点就是二叉树的根结点。中序遍历从第一个到根结点之前的结点序列为左子树,中序遍历中根结点之后的结点序列为右子树。
然后使用递归来处理根结点的左子树和右子树。
代码(Java)
1 | public TreeNode buildTree(int[] preorder, int[] inorder) { |
补充:中序遍历二叉树和前序遍历二叉树1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 // 中序遍历二叉树
public static void inorder(TreeNode root) {
if (root != null) {
preorder(root.left);
System.out.print(root.val + " ");
preorder(root.right);
}
}
// 先序遍历二叉树
public static void preorder(TreeNode root) {
if (root != null) {
System.out.print(root.val + " ");
preorder(root.left);
preorder(root.right);
}
}