题目:
题目:由前序和中序遍历构造出二叉树,再由层序遍历打印出来。
提出问题:这里面的所有元素的值都是不同的,如果相同会发生什么情况。
参考一:https://blog.csdn.net/K346K346/article/details/50970464
参考二:https://blog.csdn.net/ns_code/article/details/13169703
图片:
流程展示,代码未来有时间补上。
Construct binary tree.
p{1,2,4,7,3,5,6,8} m{4,7,2,1,5,3,8,6}
find root0 on p {1} ,seperate m to {4,7,2}{5,3,8,6}
according to m, seperate p to {2,3,7}and {3,5,6,8}
combine m{4,7,2} with p{2,4,7}
combine m{5,3,8,6} with p{3,5,6,8}
for 1: left
find root1 on p is 2, seperate m to {4,7} and null
seperate p to {4,7} and null
for 2:
combine m{4,7} with p{4,7}
combine null with null
for root2 on p is 4, seperate m to null and 7
according to m, null and 7
for 3:
null and 7.
for 1: right
find root1 on p is 3 ,seperate m to {5} and {8,6}
according to m, {5},{6,8}
for 2 :
combine m{5} and p{5}
combine m{8,6} and p{6,8}
for root2 in p is {6}, and seperate m to {8} and null
according to m, p seperated to {8} and null
done.
Level travesal using array.
// There need two pointers,left one is for travel on the roots,print and move
// forword, Another one is for put left and right child to the array. Its
// function just like queue. I think this is why queue structure be created.
root level 0
get root0{1};
root level 1
get left{2}, get right{3}; store left and right.
for left:
get left{4} and null; store left.
for right:
get left{5} and {6}; store left and right;
root level 2
for {4} :
left null, right {7}, store right
for {5} :
left null, right null
for {6} :
left {8} ,right null ,store left
root level 3
for{7} :
left null, right null;
for{8} :
left null, right null;
done.
Level travesal using queue.
root level 0:
put {1} to queue.
root level 1:
put{2} and {3} in queue, and release {1};
root level 2:
put{4} in queue, and release{2} ,put {5}{6} to queue and release{3}
root level 3:
put {7} in queue and release{4},release {5}, put {8} in queue and release {6}
root level 4:
release{7},release{8}
done.