題目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:
前序遍歷是根左右,中序遍歷是左根右,第一個節點是跟,中序中根的左邊爲左子樹,根的右邊是右子樹,因而通過遞歸就可得到答案。
代碼:
/** * Definition for binary tree * 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==null || preorder.length==0 || inorder==null || inorder.length==0){ return null; } return constructTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1); } public TreeNode constructTree(int[] preorder,int prestart,int preend,int[] inorder,int instart,int inend){ if(prestart>preend || instart>inend){ return null; } TreeNode root = new TreeNode(preorder[prestart]); for(int i=0;i<preorder.length;i++){ if(inorder[i] == preorder[prestart]){ root.left = constructTree(preorder,prestart+1,prestart+i-instart,inorder,instart,i-1); root.right = constructTree(preorder,prestart+i-instart+1,preend,inorder,i+1,inend); } } return root; } }