您的位置:首页 > 其它

二叉树之重建

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: