根據一棵樹的前序遍歷與中序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重復的元素。
例如,給出
前序遍歷 preorder =?[3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]
返回如下的二叉樹:
? ? 3
? ?/ \
? 9 ?20
? ? / ?\
? ?15 ? 7
思路:
1、前序序列第一個是根
2、根據根在中序序列中找到
3、對左右子樹做同樣的操作(操作返回的結果就是根的左右孩子)
?
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public TreeNode buildTree(int[] preorder, int[] inorder) {if(preorder.length==0)return null; TreeNode root = new TreeNode(preorder[0]);int num=0;for(int i =0; i<inorder.length; i++){if(inorder[i]==root.val){num=i;break;}}int[] preLeft = Arrays.copyOfRange(preorder,1,num+1);int[] preRight = Arrays.copyOfRange(preorder,num+1,preorder.length); int[] inoLeft = Arrays.copyOfRange(inorder,0,num);int[] inoRight = Arrays.copyOfRange(inorder,num+1,inorder.length);root.left=buildTree(preLeft,inoLeft);root.right=buildTree(preRight,inoRight);return root;}
}
?