思路:前序遍历确定根节点,中序遍历确定是根节点的左孩子和右孩子。
public TreeNode reConstructBinaryTree(int [] pre,int [] in) { TreeNode root = createBinaryTree(pre,0,pre.length-1,in,0,in.length-1); return root; } public TreeNode createBinaryTree(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn) { if(startPre > endPre || startIn > endIn) return null; TreeNode root = new TreeNode(pre[startPre]); for(int i = startIn; i <= endIn; i++) if(pre[startPre] == in[i]) { root.left = createBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); root.right = createBinaryTree(pre,endPre-endIn+i+1,endPre,in,i+1,endIn); break; } return root; }
注意:在中序序列中找到根后,要确定前序序列中左子树节点数(statrPre+1,startPre+i-startIn),右子树节点数(endPre-(endIn-i)+1)
原文:https://www.cnblogs.com/wisdomzhang/p/10483418.html