二叉树之重建
2017-06-11 21:26
246 查看
二叉树之重建
输入一颗二叉树的先序遍历和中序遍历,输出它的后序遍历。输入:
DBACEGF ABCDEFG
BCAD CBAD
输出:
ACBFGED
CDAB
var root = {value: null, left: null, right: null}; function build(root, s1, s2) { if (s1.length === 0 || s2.length === 0 ) { return; } var midnode = s2.indexOf(s1[0]); var mleft = s2.substring(0, midnode), mright = s2.substring(midnode + 1); var pleft = s1.substring(1, mleft.length + 1), pright = s1.substring(mleft.length + 1); root.value = s1[0]; root.left = newchild(); root.right = newchild(); if(root.value) { build(root.left, pleft, mleft); build(root.right, pright, mright); } } function newchild() { return {value: null, left: null, right: null} } build(root, 'DBACEGF', 'ABCDEFG'); function postrav(root) { if(root.value!==null){ postrav(root.left); postrav(root.right); console.log(root.value); } } postrav(root);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
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
[/code]
(function () {('pre.prettyprint
bf45
code').each(function () {
var lines = (this).text().split(′\n′).length;varnumbering = $('').addClass('pre-numbering').hide();
(this).addClass(′has−numbering′).parent().append(numbering);
for (i = 1; i
相关文章推荐
- 重建二叉树
- 重建二叉树
- 刷题之路----根据前序遍历和中序遍历或者后序遍历和中序遍历重建二叉树
- 【编程之美】java实现重建二叉树
- 重建二叉树--已知一个二叉树的前、中序排列,重建出该二叉树。
- 算法学习记录四(C++)--->通过前序和中序序列重建二叉树
- 剑指offer 重建二叉树
- 重建二叉树
- 二叉树的重建,遍历,求深度算法
- 由前序遍历数组和中序遍历数组重建二叉树
- 剑指offer--4.重建二叉树
- POJ 2255 Tree Recovery(二叉树重建)
- 重建二叉树
- 剑指offer 重建二叉树
- 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
- 《剑指Offer》读书笔记---面试题6:重建二叉树
- 剑指offer_重建二叉树
- Java 剑指offer之二叉树的重建
- 剑指offer——重建二叉树
- NYOJ 题目756 重建二叉树