先序遍历二叉树算法,数据结构二叉树的遍历
主题:输入某二叉树的前相遍历和中相遍历结果。 请重建这个二叉树。 假设输入的前相导线测量和中相导线测量都不包含重复的数字。 例如,输入前导导线序列{1、2、4、7、3、5、6、8}。 中顺扫描{4、7、2、1、5、3、8、6}; 重建二叉树并输出其头节点。
二叉树节点的定义如下。
publicclassbinarytreenode { intvalue;
BinaryTreeNode left;
二进制树光;
}
在二叉树的前序遍历中,第一个数字总是二叉树的根节点; 在二叉树的中顺扫描中,根节点位于通常序列的中间,左边是左边的子树的节点,右边是右边的子树的节点。
如上图所示,由于前顺序扫描的最初节点是根节点,所以该树的根节点为1,可以在中顺序扫描系列中找到根节点1的位置。 根据遍历特征,1左边的3个节点是其左边的子树的点,1右边的4个节点都是其右边的子树的节点。
在中顺遍历序列中,右3个数都是最左边的子树的节点,4个数都是右子树的节点,所以相反,如果按照前面的顺序遍历,根节点后面的3个数是左子树的节点,最后4个数是右子树的节点
现在,分割两个序列,以1为根节点左部分树的前相遍历序列{2、4、7}、中相遍历序列{4、7、2}和右部分树的前相遍历序列{3、5、6、8}、中相遍历序列{5}
我们分别找到了左、右子树的前相遍历序列和中相遍历序列,可以用同样的方法分别构造左子树和右子树。 也就是说,我们可以通过遍历来达成这个问题。
重构的二叉树的结构如下
遍历函数如下所示。 (检查数据不正确时抛出异常) )。
/**当前子树的根节点是通过按起始顺序遍历数组和按中间顺序遍历数组获得的
*
*@parampreorder先遍历数组
*@paraminorder按顺序遍历数组
*@paramstartPreorder最先遍历数组的最初数组元素的下标
*@paramendPreorder最先遍历数组最后的数组元素的下标
在*@paramstartInorder中按顺序追溯数组的第一个数组元素的下标
*@paramendInorder中,按顺序遍历数组最后的数组元素的下标
*@return当前子树的根节点
* @throws DataErrorException
*/
publicbinarytreenodeconstructcore (int [ ] preorder,int[] inorder,int startPreorder,intendPreorder,int startInorder
binarytreenoderootnode=newbinarytreenode (; introotvalue=preorder [ start preorder ];
rootNode.value=rootValue;
rootNode.left=null;
rootNode.right=null; //判断该节点是否是所希望结构的二叉树的最后一个节点
开始顺序==结束顺序(if )开始顺序==结束顺序==结束顺序[开始顺序] )返回根节点
throw new DataErrorException ('数据错误);
//按当前节点所在的降序遍历数组中的位置rootInorder
int rootInorder=startInorder; wile(inorder[rootinorder]!=rootvaluerootinorder=endin order ) {
超级用户;
}if(inorder[rootinorder]!=rootvaluerootinorder==endin order (thrownewdataerrorexception )“数据错误”);
//规划该节点的左子树//验证该节点是否还有左子树,如果有,则创建该左子树,然后返回左子树的根节点
intleftlenght=root in order-startin order; //该节点左侧子树的长度
intleftendpreorder=startpreorderleftlenght; //在前遍历中,该节点的左子树中所有节点的最后一个节点的下标
左长度0 {0}
root node.left=construct core (preorder,inorder,startPreorder 1,leftEndPreorder,startInorder,
超级订单- 1;
//计划该节点的右子树//确认该节点是否还有右子树,如果有,则创建该右子树,返回右子树的根节点
最终订单根0 (if ) {
root node.right=construct core (preorder,inorder,leftEndPreorder 1,endPreorder,rootInorder 1,endInorder );
//返回该节点
返回根节点;
}
例外函数如下。
publicclassdataerrorexceptionextendsexception (string message ) super ) message;
}
}
重构遍历函数调用二叉树函数:
/**根据首遍历序列和中序遍历序列建立二叉树
*@parampreorder先遍历数组
*@paraminorder按顺序遍历数组
*@paramlenght数组长度
*@return二叉树的根节点
*@throwsDataErrorException*/
publicbinarytreenodeconstruct (int [ ] preorder,int[] inorder,int lenght ) throwsdataerrorexception { if } lenght==0
binarytreenoderoot=construct core (preorder,inorder,0,lenght-1,0,lenght-1 ); 返回根;
}
构建的二叉树可以按照后面的顺序遍历并检查正确性:
/**后续遍历二叉树进行读取
*@paramroot*/
publicvoidreadbypostorder (binarytreenodenode ) if ) node==null ) return;
readbypostorder(node.left;
readbypostorder(node.right );
system.out.print(node.value ' );
}