java面试题--已知先序和中序遍历求后序遍历
来源:互联网 发布:淘宝夏宽 编辑:程序博客网 时间:2024/06/03 14:04
class Node {public int data;public Node left;public Node right;public Node() {}public Node(int data) {this.data = data;this.left=null;this.left=null;}}public class BinaryTree {private Node root;public BinaryTree() {root=null;}//后序遍历实现public void postOrder(Node localRoot){if(localRoot!=null){postOrder(localRoot.left);postOrder(localRoot.right);System.out.print(localRoot.data+" ");}}public void postOrder(){this.postOrder(this.root);}public void initTree(int[] preOrder,int []inOrder){this.root=this.initTree(preOrder, 0,preOrder.length-1,inOrder,0,inOrder.length);}public Node initTree(int[] preOrder, int start1, int end1, int[] inOrder, int start2,int end2) {if(start1>end1 || start2>end2){return null;}int rootData=preOrder[start1];Node head=new Node(rootData);//根节点所在的位置int rootIndex=findIndexInArray(inOrder,rootData,start2,end2);int offSet=rootIndex-start2-1;//左子树个数//构建左子树head.left=initTree(preOrder,start1+1,start1+1+offSet,inOrder,start2,start2+offSet);//构建右子树head.right=initTree(preOrder,start1+2+offSet,end1,inOrder,rootIndex+1,end2);return head;}public int findIndexInArray(int[] inOrder, int rootData, int begin,int end) {for (int i = begin; i <= end; i++) {if(inOrder[i]==rootData){return i;}}return -1;}public static void main(String[] args) {BinaryTree bt=new BinaryTree();int[]preOrder={1,2,4,8,9,5,10,3,6,7};int[]inOrder={8,4,9,2,10,5,1,6,3,7};bt.initTree(preOrder, inOrder);System.out.println("二叉树的后序遍历:");bt.postOrder();}}
阅读全文
0 0
- java面试题--已知先序和中序遍历求后序遍历
- 已知先序遍历和中序遍历求后序遍历
- 已知先序遍历和中续遍历求后序遍历
- java实现二叉树已知先序遍历和中序遍历求后序遍历
- hihocoder #1049 : 后序遍历 (已知先序遍历和中序遍历求后序遍历)
- 六、树和二叉树--(3)已知先序遍历和中序遍历求后序遍历
- 已知先序遍历和中序遍历
- 已知先序遍历和中序遍历求后序遍历——二叉树
- POJ2255-Tree Recovery 已知先序遍历和中序遍历求后序遍历
- 已知先序遍历和中序遍历 如何求后序遍历?
- 已知先序遍历和中序遍历求后序遍历——二叉树
- 已知二叉树的先序遍历和中序遍历,如何求后序遍历
- 【编程之美】3.9已知先序和中序遍历,求后序遍历+POJ-2255
- 已知二叉树的先序和中序遍历,求后序遍历及二叉树
- 已知先序遍历和中序遍历,求后序遍历 && 求二叉树中节点的最大距离
- 二叉树已知先序遍历和中序遍历得到后序遍历
- 已知前序遍历和中序遍历,求后序遍历
- 已知前序遍历和中序遍历,求后序遍历
- JDBC连接sql server 2008数据库
- Codeforces 842C
- Android Kotlin TextView跑马灯效果
- 多级指针的应用一(字符串的切割)
- IOS应用如何模糊(blur)图片
- java面试题--已知先序和中序遍历求后序遍历
- (扩展欧几里得)Modular Inverse--Zoj
- Logistic的损失函数的推导.
- Java多线程之旅(一)
- Vue.js指令
- 遍历数组
- Unity计算两点之间的距离或者向量的长度常用方法
- 安卓 使用点击事件完成双击效果的简单写法
- Struts2 入门