《剑指offer》006-重建二叉树
2017-03-21 10:01
387 查看
题目:输入前序和中序,重建二叉树。(假设前序和中序不含重复数字)。
public class ConstructBiTree { public static void main(String[] args) { // TODO Auto-generated method stub int[] pre = {1,2,4,7,3,5,6,8}; int[] in = {4,7,2,1,5,3,8,6}; // int[] pre = {1,2}; // int[] in = {2,1}; if((pre.length < 1) || (pre.length != in.length)){ System.out.println("Invalid input, cannot find a tree."); } ConstructBiTree c = new ConstructBiTree(); BiTreeNode root = c.construct(pre, in); System.out.print("preorder: "); c.t(root); } private void t(BiTreeNode node) { // TODO Auto-generated method stub if(node != null){ System.out.print(node.data + " "); t(node.left); t(node.right); } } public BiTreeNode construct(int[] pre,int[] in){ if(pre.length == 0 || pre.length != in.length){ return null; } return constructCore(pre, 0, pre.length-1, in, 0, in.length-1); } public BiTreeNode constructCore(int[] pre, int p, int q, int[] in, int i, int j){ BiTreeNode root = new BiTreeNode(pre[p]); root.left = null; root.right = null; if(p == q){ if(i == j && pre[p] == in[i]){ return root; }else{ System.out.println("Invalid input, cannot find a tree."); //throws exception } } int rootInorder = i; while(pre[p] != in[rootInorder] && rootInorder <= j){ rootInorder++; } if(rootInorder == j && pre[p] != in[rootInorder]){ System.out.println("Invalid input, cannot find a tree."); //throws exception } int leftLength = rootInorder - i; int leftPreorderEnd = p +leftLength; if(leftLength > 0){ root.left = constructCore(pre, p+1, leftPreorderEnd, in, i, rootInorder-1); } if(q - p - leftLength > 0){ root.right = constructCore(pre, leftPreorderEnd+1, q, in, rootInorder+1, j); } return root; } class BiTreeNode{ int data; BiTreeNode left; BiTreeNode right; public BiTreeNode(int data){ this.data = data; } } }
相关文章推荐
- Java笔记---剑指Offer(一:Java实现重建二叉树)
- 【剑指offer系列】 重建二叉树___6
- 剑指offer_二叉树---重建二叉树
- 剑指offer面试题7:重建二叉树 Java代码实现
- JAVA实现重建二叉树(《剑指offer》)
- 剑指Offer(4)重建二叉树
- 006重建二叉树
- 剑指offer——重建二叉树___
- 剑指offer(C++)——重建二叉树
- (php实现剑指offer)重建二叉树
- 《剑指Offer_编程题》详解重建二叉树
- 《剑指Offer》之“重建二叉树”
- 理解《剑指Offer》之面试题6 重建二叉树
- 《剑指offer》重建二叉树
- 重建二叉树-牛客网-剑指offer
- 剑指offer系列之四:重建二叉树
- 《剑指Offer》面试题-重建二叉树
- 剑指offer之重建二叉树 九度1385
- 剑指Offer:面试题6重建二叉树
- 《剑指offer》(面试题6):重建二叉树