Vous êtes sur la page 1sur 13

7/3/2017 postorder.

htm

MaximumsumofnodesinBinarytreesuchthatnotwoareadjacentGeeksforGeeks
http://www.geeksforgeeks.org/maximumsumnodesbinarytreenotwoadjacent/

pair<int,int>maxSumHelper(Node*root)
{
if(root==NULL)
{
pair<int,int>sum(0,0)
returnsum
}
pair<int,int>sum1=maxSumHelper(root>left)
pair<int,int>sum2=maxSumHelper(root>right)
pair<int,int>sum

//Thisnodeisincluded(Leftandrightchildren
//arenotincluded)
sum.first=sum1.second+sum2.second+root>data

//Thisnodeisexcluded(Eitherleftorright
//childisincluded)
sum.second=max(sum1.first,sum1.second)+
max(sum2.first,sum2.second)

returnsum
}

intmaxSum(Node*root)
{
pair<int,int>res=maxSumHelper(root)
returnmax(res.first,res.second)
}


ChangeaBinaryTreesothateverynodestoressumofallnodesinleftsubtreeGeeksforGeeks
http://www.geeksforgeeks.org/changeabinarytreesothateverynodestoressumofallnodesinleftsubtree/
/FunctiontomodifyaBinaryTreesothateverynode
/storessumofvaluesinitsleftchildincludingitsownvalue
intupdatetree(node*root)
{
if(!root)
return0
if(root>left==NULL&&root>right==NULL)
returnroot>data

//Updateleftandrightsubtrees
intleftsum=updatetree(root>left)
intrightsum=updatetree(root>right)

//Addleftsumtocurrentnode
root>data+=leftsum

//Returnsumofvaluesunderroot

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 1/13
7/3/2017 postorder.htm

returnroot>data+rightsum
}

FindCountofSingleValuedSubtreesGeeksforGeeks
http://www.geeksforgeeks.org/findcountofsinglysubtrees/
/Thisfunctionincrementscountbynumberofsingle
/valuedsubtreesunderroot.Itreturnstrueifsubtree
/underrootisSingly,elsefalse.
boolcountSingleRec(Node*root,int&count)
{
//ReturnfalsetoindicateNULL
if(root==NULL)
returntrue

//Recursivelycountinleftandrightsubtreesalso
boolleft=countSingleRec(root>left,count)
boolright=countSingleRec(root>right,count)

//Ifanyofthesubtreesisnotsingly,thenthiscannotbesingly.
if(left==false||right==false)
returnfalse

//Ifleftsubtreeissinglyandnonempty,butdata
//doesn'tmatch
if(root>left&&root>data!=root>left>data)
returnfalse

//Sameforrightsubtree
if(root>right&&root>data!=root>right>data)
returnfalse

//Ifnoneoftheaboveconditionsistrue,then
//treerootedunderrootissinglevalued,incrementcountandreturntrue.
count++
returntrue
}

Removenodesonroottoleafpathsoflength<KGeeksforGeeks
http://www.geeksforgeeks.org/removenodesrootleafpathslengthk/
boolisLeaf(Node*node)
{
return(node>left==nullptr&&node>right==nullptr)
}

//Mainfunctiontotruncategivenbinarytreetoremovenodes
//whichlieonapathhavingsumlessthank
voidtrunc(Node*&curr,intk,intsum)
{
//basecase:emptytree
if(curr==nullptr)
return

//updatesumofnodesinpathfromrootnodetocurrentnode
sum=sum+(curr>data)

//Recursivelytruncateleftandrightsubtrees
file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 2/13
7/3/2017 postorder.htm

trunc(curr>left,k,sum)
trunc(curr>right,k,sum)

//Sincewearedoingpostordertraversal,itispossible
//thatsubtreerootedatcurrentnodeisalreadytruncated
//andcurrentnodeisaleafnow

//ifcurrentnodeisaleafnodeanditspathfromrootnodehassum
//lessthantherequiredsum,removeit
if(sum<k&&isLeaf(curr))
{
//freememoryallocatedtocurrentnode
free(curr)

//setcurrentnodetonull(nodeispassedbyreference)
curr=nullptr
}
}

//Functiontotruncategivenbinarytreetoremovenodeswhichlieon
//apathhavingsumlessthank
voidtruncate(Node*&root,intk)
{
intsum=0
trunc(root,k,sum)
}

Givenabinarytree,howdoyouremoveallthehalfnodes?GeeksforGeeks
http://www.geeksforgeeks.org/givenabinarytreehowdoyouremoveallthehalfnodes/
boolisLeaf(Node*node)
{
return(node>left==nullptr&&node>right==nullptr)
}

//Functiontoconvertabinarytreetofulltreebyremovinghalfnodes
//i.e.removenodeshavingonechildren
Node*truncate(Node*root)
{
//basecase:emptytree
if(root==nullptr)
returnnullptr

//recursivelytruncatetheleftsubtreeandsubtreefirst
root>left=truncate(root>left)
root>right=truncate(root>right)

//ifcurrentnodehastwochildrenoritisleafnode,
//nothingneedstobedone

if((root>left&&root>right)||isLeaf(root))
returnroot

//ifcurrentnodehasexactlyonechild,thendeleteitandreplace
//thenodebythechildnode

Node*child=(root>left)?root>left:root>right
deleteroot
returnchild
file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 3/13
7/3/2017 postorder.htm

}


FindthemaximumpathsumbetweentwoleavesofabinarytreeGeeksforGeeks
http://www.geeksforgeeks.org/findmaximumpathsumtwoleavesbinarytree/

intmaxPathSum(structNode*root)
{
intres=INT_MIN
maxPathSumUtil(root,res)
returnres
}
//Autilityfunctiontofindthemaximumsumbetweenany
//twoleaves.Thisfunctioncalculatestwovalues:
//1)Maximumpathsumbetweentwoleaveswhichisstored
//inres.
//2)Themaximumroottoleafpathsumwhichisreturned.
//Ifonesideofrootisempty,thenitreturnsINT_MIN

intmaxPathSumUtil(structNode*root,int&res)
{
//Basecases
if(root==NULL)return0
if(!root>left&&!root>right)returnroot>data

/Findmaximumsuminleftandrightsubtree.Also
//findmaximumroottoleafsumsinleftandright
//subtreesandstoretheminlsandrs
intls=maxPathSumUtil(root>left,res)
intrs=maxPathSumUtil(root>right,res)


//Ifbothleftandrightchildrenexist
if(root>left&&root>right)
{
//Updateresultifneeded
res=max(res,ls+rs+root>data)

//Returnmaxiumpossiblevalueforrootbeingononeside
returnmax(ls,rs)+root>data
}

//Ifanyofthetwochildrenisempty,return
//rootsumforrootbeingononeside
return(!root>left)?rs+root>data:ls+root>data
}


FinddistancebetweentwogivenkeysofaBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/finddistancetwogivennodes/

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 4/13
7/3/2017 postorder.htm

//ThisfunctionreturnspointertoLCAoftwogivenvaluesn1andn2.
//Italsosetsd1,d2anddistifonekeyisnotancestorofother
//d1>Tostoredistanceofn1fromroot
//d2>Tostoredistanceofn2fromroot
//lvl>Level(ordistancefromroot)ofcurrentnode
//dist>Tostoredistancebetweenn1andn2

Node*findDistUtil(Node*root,intn1,intn2,int&d1,int&d2,int&dist,intlvl)
{
//Basecase
if(root==NULL)returnNULL

//Ifeithern1orn2matcheswithroot'skey,report
//thepresencebyreturningroot(Notethatifakeyis
//ancestorofother,thentheancestorkeybecomesLCA
if(root>key==n1)
{
d1=lvl
returnroot
}
if(root>key==n2)
{
d2=lvl
returnroot
}

//Lookforn1andn2inleftandrightsubtrees
Node*left_lca=findDistUtil(root>left,n1,n2,d1,d2,dist,lvl+1)
Node*right_lca=findDistUtil(root>right,n1,n2,d1,d2,dist,lvl+1)

//IfbothoftheabovecallsreturnNonNULL,thenonekey
//ispresentinoncesubtreeandotherispresentinother,
//SothisnodeistheLCA

if(left_lca&&right_lca)
{
dist=d1+d22*lvl
returnroot
}

//OtherwisecheckifleftsubtreeorrightsubtreeisLCA
return(left_lca!=NULL)?left_lca:right_lca
}

//Themainfunctionthatreturnsdistancebetweenn1andn2
//Thisfunctionreturns1ifeithern1orn2isnotpresentin
//BinaryTree.

intfindDistance(Node*root,intn1,intn2)
{
//Initialized1(distanceofn1fromroot),d2(distanceofn2
/fromroot)anddist(distancebetweenn1andn2)
intd1=1,d2=1,dist
file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 5/13
7/3/2017 postorder.htm

Node*lca=findDistUtil(root,n1,n2,d1,d2,dist,1)

//Ifbothn1andn2werepresentinBinaryTree,returndist

if(d1!=1&&d2!=1)
returndist

//Ifn1isancestorofn2,considern1asrootandfindlevel
//ofn2insubtreerootedwithn1

if(d1!=1)
{
dist=findLevel(lca,n2,0)
returndist
}

//Ifn2isancestorofn1,considern2asrootandfindlevel
//ofn1insubtreerootedwithn2

if(d2!=1)
{
dist=findLevel(lca,n1,0)
returndist
}

return1
}



LowestCommonAncestorinaBinaryTree|Set1GeeksforGeeks
http://www.geeksforgeeks.org/lowestcommonancestorbinarytreeset1/


structNode*findLCA(structNode*root,intn1,intn2)
{
//Basecase
if(root==NULL)returnNULL

/Ifeithern1orn2matcheswithroot'skey,report
/thepresencebyreturningroot(Notethatifakeyis
/ancestorofother,thentheancestorkeybecomesLCA
if(root>key==n1||root>key==n2)
returnroot

//Lookforkeysinleftandrightsubtrees
Node*left_lca=findLCA(root>left,n1,n2)
Node*right_lca=findLCA(root>right,n1,n2)

//IfbothoftheabovecallsreturnNonNULL,thenonekey
//ispresentinoncesubtreeandotherispresentinother,
//SothisnodeistheLCA
if(left_lca&&right_lca)returnroot

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 6/13
7/3/2017 postorder.htm

//OtherwisecheckifleftsubtreeorrightsubtreeisLCA
return(left_lca!=NULL)?left_lca:right_lca
}

Removeallnodeswhichdon'tlieinanypathwithsum>=kGeeksforGeeks
http://www.geeksforgeeks.org/removeallnodeswhichlieonapathhavingsumlessthank/

structNode*prune(structNode*root,intk)
{
intsum=0
returnpruneUtil(root,k,&sum)
}

structNode*pruneUtil(structNode*root,intk,int*sum)
{
if(root==NULL)returnNULL

//Initializeleftandrightsumsassumfromrootto
//thisnode(includingthisnode)
intlsum=*sum+(root>data)
intrsum=lsum

//Recursivelypruneleftandrightsubtrees
root>left=pruneUtil(root>left,k,&lsum)
root>right=pruneUtil(root>right,k,&rsum)

//Getthemaximumofleftandrightsums
*sum=max(lsum,rsum)

//Ifmaximumissmallerthank,thenthisnode
//mustbedeleted
if(*sum<k)
{
free(root)
root=NULL
}

returnroot
}


ConvertagiventreetoitsSumTreeGeeksforGeeks
http://www.geeksforgeeks.org/convertagiventreetosumtree/

inttoSumTree(structnode*node)
{
if(node==NULL)
return0

intold_val=node>data
node>data=toSumTree(node>left)+toSumTree(node>right)
returnnode>data+old_val
}
file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 7/13
7/3/2017 postorder.htm


CheckifagivenBinaryTreeisSumTreeGeeksforGeeks
http://www.geeksforgeeks.org/checkifagivenbinarytreeissumtree/

intisSumTree(structnode*node)
{
intls//forsumofnodesinleftsubtree
intrs//forsumofnodesinrightsubtree

/*IfnodeisNULLorit'saleafnodethen
returntrue*/
if(node==NULL||isLeaf(node))
return1

if(isSumTree(node>left)&&isSumTree(node>right))
{
//Getthesumofnodesinleftsubtree
if(node>left==NULL)
ls=0
elseif(isLeaf(node>left))
ls=node>left>data
else
ls=2*(node>left>data)

//Getthesumofnodesinrightsubtree
if(node>right==NULL)
rs=0
elseif(isLeaf(node>right))
rs=node>right>data
else
rs=2*(node>right>data)

/*Ifroot'sdataisequaltosumofnodesinleft
andrightsubtreesthenreturn1elsereturn0*/
return(node>data==ls+rs)
}

return0
}

intisSumTree(Node*root)
{
//basecase:emptytree
if(root==nullptr)
return0

//specialcase:leafnode
if(root>left==nullptr&&root>right==nullptr)
returnroot>key

//ifroot'svalueisequaltosumofallelementspresentinits
//leftandrightsubtree
if(root>key==isSumTree(root>left)+isSumTree(root>right))
return2*root>key

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 8/13
7/3/2017 postorder.htm


returnINT_MIN
}

Howtodetermineifabinarytreeisheightbalanced?GeeksforGeeks
http://www.geeksforgeeks.org/howtodetermineifabinarytreeisbalanced/

/*Thefunctionreturnstrueifrootisbalancedelsefalse
Thesecondparameteristostoretheheightoftree.
Initially,weneedtopassapointertoalocationwithvalue
as0.Wecanalsowriteawrapperoverthisfunction*/

boolisBalanced(structnode*root,int*height)
{
/*lh>Heightofleftsubtree
rh>Heightofrightsubtree*/
intlh=0,rh=0

/*lwillbetrueifleftsubtreeisbalanced
andrwillbetrueifrightsubtreeisbalanced*/
intl=0,r=0

if(root==NULL)
{
*height=0
return1
}

/*Gettheheightsofleftandrightsubtreesinlhandrh
Andstorethereturnedvaluesinlandr*/
l=isBalanced(root>left,&lh)
r=isBalanced(root>right,&rh)

/*Heightofcurrentnodeismaxofheightsofleftand
rightsubtreesplus1*/
*height=(lh>rh?lh:rh)+1

/*Ifdifferencebetweenheightsofleftandright
subtreesismorethan2thenthisnodeisnotbalancedsoreturn0*/
if((lhrh>=2)||(rhlh>=2))
return0

/*Ifthisnodeisbalancedandleftandrightsubtrees
arebalancedthenreturntrue*/
elsereturnl&&r
}


FindmaximumsumroottoleafpathinabinarytreeTechieDelight
http://www.techiedelight.com/findmaximumsumroottoleafpathbinarytree/
//Functiontoprintmaximumsumroottoleafpathinagivenbinarytree
voidfindMaxSumPath(Node*root)
{
intsum=rootToLeafSum(root)
file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 9/13
7/3/2017 postorder.htm

cout<<"Maximumsumis"<<sum<<endl
cout<<"Maximumsumpathis:"

printPath(root,sum)
}

//Functiontocalculatemaximumroottoleafsuminabinarytree
introotToLeafSum(Node*root)
{
//basecase:treeisempty
if(root==nullptr)
return0

//calculatemaximumnodetoleafsumforleftchild
intleft=rootToLeafSum(root>left)

//calculatemaximumnodetoleafsumforrightchild
intright=rootToLeafSum(root>right)

//considermaximumsumchild
return(left>right?left:right)+root>data
}


boolprintPath(Node*root,intsum)
{
//basecase
if(sum==0)
returntrue

//basecase
if(root==nullptr)
returnfalse

//recurseforleftandrightsubtreewithreducedsum
boolleft=printPath(root>left,sumroot>data)
boolright=printPath(root>right,sumroot>data)

//printcurrentnodeifitliesonpathhavinggivensum
if(left||right)
cout<<root>data<<""

returnleft||right
}



SinknodescontainingzerotothebottomofthebinarytreeTechieDelight
http://www.techiedelight.com/sinknodescontainingzerobottombinarytree/
voidsink(Node*root)
{
//basecase:treeisempty
if(root==nullptr)
return

//ifleftsubtreeexists&leftchildhasnonzerovalue
if(root>left&&root>left>data!=0)
{
//swapdataofcurrentnodewithitsleftchild
swap(root>data,root>left>data)
file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 10/13
7/3/2017 postorder.htm


//recurseforleftsubtree
sink(root>left)
}

//ifrightsubtreeexists&rightchildhasnonzerovalue
elseif(root>right&&root>right>data!=0)
{
//swapdataofcurrentnodewithitsrightchild
swap(root>data,root>right>data)

//recurseforrightsubtree
sink(root>right)
}
}

//Mainfunctiontosinknodeshavingzerovaluetothebottom
//ofthebinarytree
voidsinkNodes(Node*&root)
{
//basecase:treeisempty
if(root==nullptr)
return

//fixleftsubtreeandrightsubtreefirst
sinkNodes(root>left)
sinkNodes(root>right)

//sinkcurrentnodeithasvalue0
if(root>data==0)
sink(root)
}
FindancestorsofgivennodeinaBinaryTreeTechieDelight
http://www.techiedelight.com/findancestorsofgivennodebinarytree/
boolprintAncestors(Node*root,intnode)
{
//basecase
if(root==nullptr)
returnfalse

//returntrueifgivennodeisfound
if(root>data==node)
returntrue

//searchnodeinleftsubtree
boolleft=printAncestors(root>left,node)

//searchnodeinrightsubtree
boolright=printAncestors(root>right,node)

//ifgivennodeisfoundineitherleftorrightsubtree,
//currentnodeisanancestorofgivennode
if(left||right)
cout<<root>data<<""

//returntrueifnodeisfound
returnleft||right
}

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 11/13
7/3/2017 postorder.htm

ConvertbinarytreetoitsmirrorTechieDelight
http://www.techiedelight.com/convertbinarytreetoitsmirror/
Convertbinarytreetoitsmirror

boolconvertToMirror(Node*root)
{
//basecase:iftreeisempty
if(root==nullptr)
returntrue

//convertleftsubtree
convertToMirror(root>left)

//convertrightsubtree
convertToMirror(root>right)

//swapleftsubtreewithrightsubtree
swap(root>left,root>right)
}

http://www.techiedelight.com/inplaceconvertatreesumtree/

DeletegivenBinaryTree|Iterative&RecursiveTechieDelight
http://www.techiedelight.com/deletegivenbinarytreeiterativerecursive/
voiddeleteBinaryTree(Node*&root)
{
//Basecase:emptytree
if(root==nullptr)
return

//deleteleftandrightsubtreefirst(Postorder)
deleteBinaryTree(root>left)
deleteBinaryTree(root>right)

//Afterdeletingleftandrightsubtree,deletethecurrentnode
deleteroot

//setrootasNULLbeforereturning
root=nullptr
}

Calculateheightofbinarytree|Iterative&RecursiveTechieDelight
http://www.techiedelight.com/calculateheightbinarytreeiterativerecursive/

Calculateheightofbinarytree
intheight(Node*root)
{
//Basecase:emptytreehasheight0
if(root==nullptr)
return0

//recurseforleftandrightsubtreeandconsidermaximumdepth
returnmax(height(root>left),height(root>right))+1
}

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 12/13
7/3/2017 postorder.htm

FinddiameterofabinarytreeTechieDelight
http://www.techiedelight.com/finddiameterofabinarytree/


//Functiontofinddiameterofthebinarytree.Notethatthefunction
//returnstheheightofthesubtreerootedatgivennodeanddiameter
//isupdatedwithinthefunctionasitispassedbyreference
intgetDiameter(Node*root,int&diameter)
{
//basecase:treeisempty
if(root==nullptr)
return0

//getheightsofleftandrightsubtrees
intleft_height=getDiameter(root>left,diameter)
intright_height=getDiameter(root>right,diameter)

//calculatediameter"through"thecurrentnode
intmax_diameter=left_height+right_height+1

//UpdateMaximumDiameter(Notethatdiameter"excluding"thecurrent
//nodeinsubtreerootedatcurrentnodeisalreadyupdatedaswe're
//doingpostordertraversal)
diameter=max(diameter,max_diameter)

//importantreturnheightofsubtreerootedatcurrentnode
returnmax(left_height,right_height)+1
}

//Functiontofinddiameterofthebinarytree
intgetDiameter(Node*root)
{
intdiameter=0
getDiameter(root,diameter)

returndiameter
}

file:///C:/Users/akash/Desktop/placement%20docs/postorder.htm 13/13

Vous aimerez peut-être aussi