剑指offer面试题6:重建二叉树
2016-03-24 15:58
549 查看
1、题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
2、Java创建二叉树:
public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1); return root; } //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6} private TreeNode reConstructBinaryTree(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(in[i]==pre[startPre]) { root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); } return root; } }
2、Java创建二叉树:
public class TreeTest { public static String[] str; public static int count; /** * 静态内部类,定义二叉树节点 */ static class TreeNode { public String data; TreeNode lchild; TreeNode rchild; public TreeNode(String x) { this.data = x; } } /** * 根据前序序列递归构建二叉树 * * @return */ public static TreeNode createBtree() { TreeNode root = null; if (count >= str.length || str[count++].equals("#")) { root = null; } else { root = new TreeNode(str[count - 1]); root.lchild = createBtree(); root.rchild = createBtree(); } return root; } /** * 前序遍历 * * @param root */ public static void preTraverse(TreeNode root) { if (root != null) { System.out.print(root.data + " "); preTraverse(root.lchild); preTraverse(root.rchild); } } /** * 中序遍历 * * @param root */ public static void inTraverse(TreeNode root) { if (root != null) { inTraverse(root.lchild); System.out.print(root.data + " "); inTraverse(root.rchild); } } /** * 后序遍历 * * @param root */ public static void postTraverse(TreeNode root) { if (root != null) { postTraverse(root.lchild); postTraverse(root.rchild); System.out.print(root.data + " "); } } public static void main(String args[]) { Scanner cin = new Scanner(System.in); while (cin.hasNext()) { String s = cin.nextLine(); str = s.split(","); count = 0; TreeNode root = createBtree(); // 前序遍历 preTraverse(root); System.out.println(); // 中序遍历 inTraverse(root); System.out.println(); // 后序遍历 postTraverse(root); System.out.println(); } cin.close(); } }
相关文章推荐
- 程序员:让你的腹部瞬间显瘦,只差一个动作!
- 女码农献丑-企业智能机器人客服(图灵机器人)
- day04 面试题Schema约束与DTD约束的区别
- 前端面试题笔记
- 从武侠小说到程序员面试
- 前端工作面试问题
- 程序员:让你的腹部瞬间显瘦,只差一个动作!
- iOS 面试题总结(一)
- IQ智商测试题积累
- 操作系统面试题(更新中。。)
- 程序员读书清单
- 数据库面试题(更新中。。。)
- 程序员的八种级别
- [Facebook 面试题]Meeting roomII 变形题
- 关于离职、面试、面试题
- JAVA 面试题(更新中。。)
- 线程安全性---面试题--i++的线程安全性问题
- PHP中级面试经历
- 面试 ABAPer的一些感想
- Android 面试题总结(一)