树的计数问题和通过一个中序遍历序列和一个先序遍历序列来确定一棵二叉树
2016-06-07 17:47
489 查看
通过一个中序遍历序列和一个先序遍历序列来确定一棵二叉树
用例为://先序:abcdefg 中序: cbedafg
结果为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import java.util.ArrayList; //通过一个中序遍历序列和一个先序遍历序列来确定一棵二叉树 public class TestCase2{ //preOrders先序遍历序列 midOrders中序遍历序列 public static TreeCase getTree(TreeCase tree,ArrayList<Character> preOrders,ArrayList<Character> midOrders){ if (midOrders.isEmpty()) return null ; tree = new TreeCase(); tree.data = preOrders.get( 0 ); //找到中间位置 int index = midOrders.indexOf(preOrders.get( 0 )); //找到当前根节点在中序中的位置,位置左边就是该根节点的左子树 preOrders.remove( 0 ); //右边就是其右子树 if (midOrders.size() == 1 ) return tree; //已经是叶子节点了 ArrayList<Character> arr1 = new ArrayList<>(); //左子树的中序序列 for ( int i= 0 ;i<index;i++){ arr1.add(midOrders.remove( 0 )); } midOrders.remove( 0 ); //右子树的中序序列 tree.lchild = getTree(tree.lchild,preOrders,arr1); //构造左子树 tree.rchild = getTree(tree.rchild,preOrders,midOrders); //构造右子树 return tree; } public static void main(String[] args){ ArrayList<Character> arr1 = new ArrayList<>( 7 ); ArrayList<Character> arr2 = new ArrayList<>( 7 ); //先序:abcdefg 中序: cbedafg arr1.add( 'a' ); arr1.add( 'b' ); arr1.add( 'c' ); arr1.add( 'd' ); arr1.add( 'e' ); arr1.add( 'f' ); arr1.add( 'g' ); arr2.add( 'c' ); arr2.add( 'b' ); arr2.add( 'e' ); arr2.add( 'd' ); arr2.add( 'a' ); arr2.add( 'f' ); arr2.add( 'g' ); TreeCase tree = null ; tree = TestCase2.getTree(tree, arr1, arr2); } } class TreeCase{ char data; TreeCase lchild; TreeCase rchild; } |
相关文章推荐
- C#数据结构之顺序表(SeqList)实例详解
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- 数据结构之Treap详解
- 用C语言举例讲解数据结构中的算法复杂度结与顺序表
- C#数据结构之堆栈(Stack)实例详解
- C#数据结构之双向链表(DbLinkList)实例详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)