Using DFS to traverse the node and build the A tree. For a node, it has following properties:
If its a left child node of its parent and then the left boundary start of the inorder array is its parent's location in I Norder Array. Let Inorderpos is the location of the current node, we can find it in the "left" of the parent node POS in inorder array. if Inorderpos = = start+1, this means the current node have no left child, set it to IS null. Otherwise, it had a left child node, and the postion of its left child node was preorderpos+1 in Preorderpos array. Then we can go into it left child, and update end to is current node ' s In-order pos. If Inorderpos = = end-1; It means current node have no right child and set it to IS null. Otherwise, it had a right child node, and the position of its right node was Preorderpos+inorderpos-start, update start to Be current node ' s In-order pos.
Code:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { intLen =preorder.length; if(len = = 0)return NULL; returnDfsaddnode (Preorder, inorder,-1, Len, 0); } PublicTreeNode Dfsaddnode (int[] Preorder,int[] inorder,intStartintEndintPreorderpos) { intval =Preorder[preorderpos]; TreeNode node=NewTreeNode (Val); intInorderpos =-1; for(inti = start+1; I < end; i++){ if(Inorder[i] = = val) Inorderpos =i; } if(Inorderpos = = start+1) Node.left =NULL; ElseNode.left = Dfsaddnode (preorder, inorder, start, Inorderpos, preorderpos+1); if(Inorderpos = = end-1) Node.right =NULL; ElseNode.right = Dfsaddnode (preorder, inorder, Inorderpos, end, preorderpos+inorderpos-start); returnnode; } /*public int Inorderpos (int[] inorder, int. start, int end, int val) {for (int i = start+1; i < end; i++) { if (inorder[i] = = val) return i; } return-1; } */}
A little advance is so, we can use a hashmap to record the postion of inorder element. To avoid Unnecessay duplicative look through in the inorder array.
Jan 28-construct Binary Tree from preorder and inorder; Tree; DFS; Array