Question:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Analysis:
给出一棵树的前序遍历和中序遍历,构建这棵二叉树。
注意: 你可以假设树中不存在重复的关键码。
思路:
前序遍历和中序遍历肯定是可以唯一确定一棵二叉树的。
前序遍历的第一个节点肯定是根节点,得到根节点后再到中序遍历中,可以很容易的找出左子树和右子树,然后这样递归的找根节点,确立左子树、右子树……
Answer:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { return buildTreeHelper(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); } public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int pre1, int pre2, int in1, int in2) { if(pre1 > pre2) return null; int pivot = pre1; int i = in1; for(; i<in2; i++) { if(preorder[pivot] == inorder[i]) break; } TreeNode t = new TreeNode(preorder[pivot]); int len = i - in1; t.left = buildTreeHelper(preorder, inorder, pivot+1, pivot+len, in1, i-1); t.right = buildTreeHelper(preorder, inorder, pivot+len+1, pre2, i+1, in2); return t; } }