LeetCode | Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
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; } * } */
//从先序和中序遍历恢复树,主要思想是利用递归,抽象算法如下: // TreeNode root = preorder[0]; // root.left = buildTree(preorder[leftsubtree], inorder[leftsubtree]); // root.right = buildTree(preorder[rightsubtree], inorder[rightsubtree]); // 先序遍历数组的首一定是root,然后根据root.val去中序遍历中定位root的位置 // 算法的关键就在于每次递归时在先序与中序遍历中定位出leftsubtree与rightsubtree
public class Solution { public int findRoot(int[] inorder, int key){ //在中序遍历中定位root的位置下标 if(inorder.length==0) return -1; int index = -1; for(int i=0; i<inorder.length; i++){ if(inorder[i]==key){ index = i;break; } } return index; } //实现重建树的逻辑,[prestart,preend]表示先序遍历的位置,[instart,inend]表示中序遍历的位置 public TreeNode buildTree(int[] preorder, int[] inorder, int prestart, int preend, int instart, int inend){ if(preorder.length==0 || inorder.length==0) return null; if(instart>inend) return null; TreeNode root = new TreeNode(preorder[prestart]); int index = findRoot(inorder, root.val); //index表示root在中序遍历inorder中的位置 //下面两行要自己画图才能看出来, preorder[leftsubtree]= preorder[prestart+1至prestart+1+index-1-instart] // 以在先序、中序遍历中定位左子树为例: inorder[leftsubtree]= inorder[instart至index-1] root.left = buildTree(preorder, inorder, prestart+1, prestart+1+index-1-instart, instart, index-1); root.right = buildTree(preorder, inorder, prestart+1+index-1-instart+1, preend, index+1, inend); return root; } //******leetcode主函数****** public TreeNode buildTree(int[] preorder, int[] inorder) { return buildTree(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1); } }