[LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal Java
题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
题意及分析:给出一棵树的先序遍历和中序遍历,要求给出给出该二叉树。先序遍历第一个节点肯定是根节点,那么这样就可以利用中序遍历找出树的左右子树,然后分别得到左右子树的先序遍历和中序遍历,再分别对左右子树进行查找分割即可。这里利用递归。
代码:
/** * 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) { if(preorder.length==0) return null; TreeNode root = new TreeNode(preorder[0]); //先序遍历的第一个点肯定是根节点 build(root,preorder,inorder); return root; } public void build(TreeNode root,int[] preorder, int[] inorder) { //递归,分别将先序遍历分为左右子树递归 int rootVal = root.val; int splitIndex = 0; for(int i=0;i<inorder.length;i++){ if(rootVal==inorder[i]){ //找到分割左右子树的点 splitIndex=i; //中序遍历分割点,该点前面为左子树,后面为右子树 } } int leftCount=splitIndex; //这样得到左子树的节点数,对先序遍历第二个点开始遍历leftCount点的子数组就是左子树先序遍历的结果 int[] leftPreorder = Arrays.copyOfRange(preorder,1,1+leftCount); //左子树先序遍历 int[] leftInorder=Arrays.copyOfRange(inorder,0,leftCount); //右子树先序遍历 if(leftPreorder.length!=0){ root.left=new TreeNode(leftPreorder[0]); //若有左子树,那么添加左子节点 build(root.left,leftPreorder,leftInorder); } int[] rightPreorder = Arrays.copyOfRange(preorder,leftCount+1,preorder.length); int[] rightInorder = Arrays.copyOfRange(inorder,leftCount+1,inorder.length); if(rightPreorder.length!=0){ root.right=new TreeNode(rightPreorder[0]); build(root.right,rightPreorder,rightInorder); } } }