8.3Writeamethodthatreturnsallsubsetsofaset.powerSet(i)=
[powerSet(i-1)]*ITEMi+//Addnewitemintoeachexistingset
[pwerSet(i-1)]+//Existingset
ITEMi//singlenewitem.
powerSet(1)=ITEM1.
<T>Set<Set<T>>powerSet(Set<T>set)
{
if(set==null||se..
分类:
其他好文 时间:
2014-12-01 10:16:15
阅读次数:
146
8.1WriteamethodtogeneratethenthFibonaccinumber.classFibonacci()
{
voidinit()
{
a=0;
b=1;
}
intnext()
{
inttoReturn=a+b;
a=b;
b=toReturn;
returntoReturn;
}
}
{
Fibonaccifibo=init();
for(n)
{
toReturn=fibo.next();
}
returntoReturn;
}
fibonacci(intn)
{
if(..
分类:
其他好文 时间:
2014-11-28 10:30:25
阅读次数:
149
4.7Youhavetwoverylargebinarytrees:T1,withmillionsofnodes,andT2,withhundredsofnodes.CreateanalgorithmtodecideifT2isasubtreeofT1.//Itwilliteratemaintree(millions)nodes.
//Toobad.
booleanisSubTree(Nodemain,Nodesub)
{
if(main==null)
returnnull;
if(main==sub)
r..
分类:
其他好文 时间:
2014-11-28 10:30:24
阅读次数:
157
4.2Givenadirectedgraph,designanalgorithmtofindoutwhetherthereisaroutebetweentwonodes.Node
{
List<Node>neighbours;
}
booleanisConnected(Nodefrom,Nodeto)
{
Stack<Node>toVisit=initStack();
Set<Node>seen=initSet();
toVisit.push(from);
while..
分类:
其他好文 时间:
2014-11-27 08:05:32
阅读次数:
147
3.5ImplementaMyQueueclasswhichimplementsaqueueusingtwostacks.interfaceQueue<T>
{
enqueue(Tt);
Tdequeue();
}
classMyQueue<T>implementsQueue<T>
{
MyQueue()
{
//Initstackss1ands2;
...
}
//O(n)
enqueue(Tt)
{
while(!s2.isEmpty())
{
s1.push(s2..
分类:
其他好文 时间:
2014-11-27 08:05:14
阅读次数:
140
4.3Givenasorted(increasingorder)array,writeanalgorithmtocreateabinarytreewithminimalheight.[1,2,4,5,6]CreateaBTwithminheight.=>balancedtree.Nodebuild(intarray)
{
returnbuild(array,0,array.length-1,null);
}
O(logn)
privateNodebuild(int[]array,intfrom,int..
分类:
其他好文 时间:
2014-11-27 08:04:10
阅读次数:
189
4.1Implementafunctiontocheckifatreeisbalanced.Forthepurposesofthisquestion,abalancedtreeisdefinedtobeatreesuchthatnotwoleafnodesdifferindistancefromtherootbymorethanone.Abalancedtree?http://en.wikipedia.org/wiki/Self-balancing_binary_search_treeIteratethetr..
分类:
其他好文 时间:
2014-11-27 08:03:52
阅读次数:
190
4.4Givenabinarysearchtree,designanalgorithmwhichcreatesalinkedlistofallthenodesateachdepth(i.e.,ifyouhaveatreewithdepthD,you’llhaveDlinkedlists).List<List<Node>>build(Noderoot)
{
List<List<Node>>toReturn=initList();
build(root,0,toR..
分类:
其他好文 时间:
2014-11-27 08:02:53
阅读次数:
189
3.6Writeaprogramtosortastackinascendingorder.Youshouldnotmakeanyassumptionsabouthowthestackisimplemented.Thefollowingaretheonlyfunctionsthatshouldbeusedtowritethisprogram:push|pop|peek|isEmpty.interfaceStack<T>
{
push(Tt);
Tpop();
Tpeek();
booleanisEm..
分类:
其他好文 时间:
2014-11-27 08:02:46
阅读次数:
156
4.5Writeanalgorithmtofindthe‘next’node(i.e.,in-ordersuccessor)ofagivennodeinabinarysearchtreewhereeachnodehasalinktoitsparent.//BST.
classNode
{
Nodeparent;
Nodeleft;
Noderight;
}
Nodemin(Nodenode)
{
if(node==null)
returnnull;
while(node.left!=null)
nod..
分类:
其他好文 时间:
2014-11-27 08:01:56
阅读次数:
218