algorithm – 在具有最小空间的网络上传递二叉树

我最近遇到亚马逊提出的面试问题:

给定要通过网络传递的二叉树.如何在最小的空间内传递这棵树?

好的,我对上述问题的解决方法是:

>我们可以将树的顺序存储在数组中,同时在另一个数组中存储预订(或后序或级别顺序),然​​后将2个数组传递到网络中.这会占用大量空间.所以拒绝它,我提出了其他解决方案.
>我们将逐级传递树的每个节点以及有关它的左右子节点的一些信息.

方法2

附加信息以及节点:

如果留下孩子== NULL&& right child == NULL与节点一起传递00

如果留下孩子!= NULL&& right child == NULL与节点一起传递10

如果留下孩子== NULL&& right child!= NULL与节点一起传递01

如果留下孩子!= NULL&& right child!= NULL传递11和节点一起

让我们看一下第二种方法的例子

等级明智

>传递节点(2)和11
>传递节点(7)和11
>传递节点(5)和11
>传递节点(2)和00
>传递节点(6)和11
>传递节点(9)和10
>传递节点(5)和00
>传递节点(11)和00
>传递节点(4)和00

如果我是正确的,那么通过这种方式,您可以通过轻松检查附加信息来重建网络另一侧的树(并原谅我,如果我错了)你使用的内存较少,因为你只是一次传递节点的值和附加信息而不是传递整个树.

好的,现在我有2个问题:

>我的方法2是否正确,或者是否存在我可能错过的特殊情况.
>除了上述2之外,还有更有效的方法将树发送到网络上吗?

最佳答案

This is more of a kind of question you are not expected to come up with an exact solution. All u need is to reason out soundly.

A better and efficient approach for passing the binary tree to a network would be to send its preorder traversal alone. Since u might have read that using a preorer traversal alone (if we have the entire info of a tree) is sufficent to create a tree. You can pass the entire binary tree via a single preorder traversal.
For eg . if ur tree is     1   /    \2      3 Then if u want to send this tree to a network do its preorder traversal as 1 2 # # 3 # #… store it an array and send it via packets preferably packet switching.
what I have done is that for every null left or right child(i.e if its left or right child or both is not present), I have put a ‘#’ sentinel.   Now the user on the other side of the network would decode it easily using a stack-based approach which u might have learnt in your basic data-structure course. The solution u gave is also correct and I dont think there is any corner case for it but it also is not very space efficient 1. First, whether u send a tree level by level or in 2 arrays as u said above , u will be passing them as packets on a network and not as entire arrays(so sending is not a big concern when size of a single packet has a limit. U can send it via multiple packets). But for getting the info about a node and its children , u would require additonal space to store ur answer which is an overhead .. 2. u would be doing a level order traversal which on an average is more space consuming than a stack based o(height) space appraoch. BTW, u seem to be preparing for amazon. All the best.

点赞