二叉树序列---根据后序和中序系列或前序和中序序列构造二叉树
2016-11-02 15:13
393 查看
1、根据前序遍历序列和中序遍历序列,构造二叉树(或求后序遍历序列);
2、根据后序遍历序列和中序遍历序列,构造二叉树(或求前序遍历序列);
public Node buildTree(int[] preOrder,int[] inOrder){ Node root=buildTree(preOrder,0,preOrder.length-1,inOrder,0,inOrder.length-1); return root; } private Node buildTree(int[] preOrder,int pstart,int pend,int[] inOrder,int istart,int iend){ if(pstart>pend || istart>iend){ return null; } Node root=new Node(preOrder[pstart]); int index=findIndexInArray(preOrder[pstart],inOrder,istart,iend); root.left=buildTree(preOrder,pstart+1,pstart+index-istart,inOrder,istart,index-1); root.right=buildTree(preOrder,pstart+index-istart+1,pend,inOrder,index+1,iend); return root; } private int findIndexInArray(int x, int[] inOrder, int pstart, int pend) { for(int i=pstart;i<=pend;i++){ if(inOrder[i]==x){ return i; } } return -1; }
2、根据后序遍历序列和中序遍历序列,构造二叉树(或求前序遍历序列);
public Node buildTree(int[] inOrder,int[] postOrder){ Node root=buildTree(inOrder,0,inOrder.length-1,postOrder,0,postOrder.length-1); return root; } private Node buildTree(int[] inOrder,int istart,int iend,int[] postOrder,int pstart,int pend){ if(pstart>pend || istart>iend){ return null; } Node root=new Node(postOrder[pend]); int index=findIndexInArray(postOrder[pend],inOrder,istart,iend); root.left=buildTree(inOrder,istart,index-1,postOrder,pstart,pstart+index-istart-1); root.right=buildTree(inOrder,index+1,iend,postOrder,pstart+index-istart,pend-1); return root; } private int findIndexInArray(int x, int[] inOrder, int istart, int iend) { for(int i=istart;i<=iend;i++){ if(inOrder[i]==x){ return i; } } return -1; }
相关文章推荐
- 二叉树系列——根据前序和中序、中序和后序构建二叉树
- 二叉树:根据二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- 通过二叉树的中序和后序遍历序列构造二叉树(非递归)
- 二叉树根据先序,中序创建二叉树,后序,中序创建二叉树,层次序列,中序遍历创建二叉树。
- 旧话重提,根据先序和中序遍历构造二叉树并后序遍历验证之
- 根据中序和层次遍历序列,构造二叉树
- 【构建二叉树】02根据中序和后序序列构造二叉树【Construct Binary Tree from Inorder and Postorder Traversal】
- 数据结构Step by Step之树(1)- 二叉树 前序、中序、后序 LeetCode105根据前序中序的顺序构造树
- C++ 根据前序遍历序列和中序遍历序列可以构造唯一的二叉树
- 实现由先序、中序序列构造二叉树的算法,实现由后序、中序序列构造二叉树的算法
- 根据前序遍历序列和中序遍历序列构造二叉树
- 根据前序遍历序列和中序遍历序列构造二叉树
- 【构建二叉树】01根据前序和中序序列构造二叉树【Construct Binary Tree from Preorder and Inorder Traversal】
- 根据二叉树的前序遍历序列和中序遍历序列求二叉树的后序遍历序列
- 根据中序序列和前序序列,求二叉树的后序序列
- 先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- JAVA 根据二叉树的前序和中序获得后序,后序和中序获得前序
- [置顶] 数据结构之 二叉树的构造与遍历(先序,中序,后序,层次)
- 根据前序遍历序列和中序遍历序列构造二叉树算法
- poj2255 根据二叉树的前序和中序遍历 求出树的后序遍历