You are on page 1of 16

7/3/2017 treepreorder.

htm

PREORDER
ValidateBinarySearchTree(LeetCode)
http://ruhinraihan.blogspot.in/2016/10/validatebinarysearchtreeleetcode.html

boolisValidBST(TreeNode*root){
return(checkBST(root,NULL,NULL))
}

boolcheckBST(TreeNode*root,TreeNode*min,TreeNode*max)
{
if(root==NULL)returntrue
if(min&&root>val<=min>val)returnfalse
if(max&&root>val>=max>val)returnfalse

if(!checkBST(root>left,min,root))returnfalse
if(!checkBST(root>right,root,max))returnfalse
returntrue
}
}


PrintallksumpathsinabinarytreeGeeksforGeeks
http://www.geeksforgeeks.org/printksumpathsbinarytree/
voidprintKPathUtil(Node*root,vector<int>&path,intk)
{

if(!root)return//emptynode
path.push_back(root>data)//addcurrentnodetothepath
printKPathUtil(root>left,path,k)//checkifthere'sanyksumpathintheleftsubtree.
printKPathUtil(root>right,path,k)//checkifthere'sanyksumpathintherightsubtree.

intf=0
for(intj=path.size()1j>=0j)
{
f+=path[j]

//Ifpathsumisk,printthepath
if(f==k)
printVector(path,j)
}

//checkifthere'sanyksumpaththatterminatesatthisnodeTraversetheentirepathas
//therecanbenegativeelementstoo

//Removethecurrentelementfromthepath
path.pop_back()
}

//AwrapperoverprintKPathUtil()
voidprintKPath(Node*root,intk)
{
vector<int>path

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

printKPathUtil(root,path,k)
}


Checkwhetherabinarytreeisacompletetreeornot|Set2(RecursiveSolution)GeeksforGeeks
http://www.geeksforgeeks.org/checkwhetherbinarytreecompletenotset2recursivesolution/
unsignedintcountNodes(structNode*root)
{
if(root==NULL)
return(0)
return(1+countNodes(root>left)+countNodes(root>right))
}

boolisComplete(structNode*root,unsignedintindex,unsignedintnumber_nodes)
{
if(root==NULL)//Anemptytreeiscomplete
return(true)

if(index>=number_nodes)
return(false)//Ifindexassignedtocurrentnodeis
morethannumberofnodesintree,thentreeisnotcomplete


//Recurforleftandrightsubtrees
return(isComplete(root>left,2*index+1,number_nodes)&&
isComplete(root>right,2*index+2,number_nodes))
}


FindsumofallleftleavesinagivenBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/findsumleftleavesgivenbinarytree/
intleftLeavesSum(Node*root)
{
//Initializeresult
intres=0

//UpdateresultifrootisnotNULL
if(root!=NULL)
{

if(isLeaf(root>left))//IfleftofrootisNULL,thenaddkeyofleftchild
res+=root>left>key
else//Elserecurforleftchildofroot
res+=leftLeavesSum(root>left)

//Recurforrightchildofrootandupdateres
res+=leftLeavesSum(root>right)
}

//returnresult

file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 2/16
7/3/2017 treepreorder.htm

returnres
}


FindtheclosestleafinaBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/findclosestleafbinarytree/

intclosestDown(structNode*root)
{
//Basecases
if(root==NULL)
returnINT_MAX
if(root>left==NULL&&root>right==NULL)
return0

//Returnminimumofleftandright,plusone
return1+getMin(closestDown(root>left),closestDown(root>right))
}

//Returnsdistanceofthecloestleaftoagivenkey'k'.Thearray
//ancestorsisusedtokeeptrackofancestorsofcurrentnodeand
//'index'isusedtokeeptrackofcurremtindexin'ancestors[]'

intfindClosestUtil(structNode*root,chark,structNode*ancestors[],
intindex)
{
if(root==NULL)returnINT_MAX
if(root>key==k)
{
intres=closestDown(root)

//Traverseallancestorsandupdateresultifanyparentnodegivessmallerdistance
for(inti=index1i>=0i)
res=getMin(res,indexi+closestDown(ancestors[i]))
returnres
}

//Ifkeynodefound,storecurrentnodeandrecurforleftandrightchildrens
ancestors[index]=root
returngetMin(findClosestUtil(root>left,k,ancestors,index+1),
findClosestUtil(root>right,k,ancestors,index+1))

}

//Themainfunctionthatreturnsdistanceoftheclosestkeyto'k'.It
//mainlyusesrecursivefunctionfindClosestUtil()tofindthecloses
//distance.

intfindClosest(structNode*root,chark)
{
//Createanarraytostoreancestors
//Assumptiom:Maximumheightoftreeis100
structNode*ancestors[100]

file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 3/16
7/3/2017 treepreorder.htm

returnfindClosestUtil(root,k,ancestors,0)
}


SerializeandDeserializeaBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/serializedeserializebinarytree/

voidserialize(Node*root,FILE*fp)
{
//IfcurrentnodeisNULL,storemarker
if(root==NULL)
{
fprintf(fp,"%d",MARKER)
return
}

//Else,storecurrentnodeandrecurforitschildren
fprintf(fp,"%d",root>key)
serialize(root>left,fp)
serialize(root>right,fp)
}

//Thisfunctionconstructsatreefromafilepointedby'fp'
voiddeSerialize(Node*&root,FILE*fp)
{
//Readnextitemfromfile.Iftheerearenomoreitemsornextitemismarker,thenreturn

intval
if(!fscanf(fp,"%d",&val)||val==MARKER)
return

//Elsecreatenodewiththisitemandrecurforchildren
root=newNode(val)
deSerialize(root>left,fp)
deSerialize(root>right,fp)
}


ReversealternatelevelsofaperfectbinarytreeGeeksforGeeks
http://www.geeksforgeeks.org/reversealternatelevelsbinarytree/

voidreverseAlternate(structNode*root)
{
preorder(root>left,root>right,0)
}

voidpreorder(structNode*root1,structNode*root2,intlvl)
{
if(root1==NULL||root2==NULL)
return

//Swapsubtreesifleveliseven
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 4/16
7/3/2017 treepreorder.htm

if(lvl%2==0)
swap(root1>key,root2>key)
preorder(root1>left,root2>right,lvl+1)
preorder(root1>right,root2>left,lvl+1)Recurforleftandrightsubtrees
(Note:leftofroot1ispassedandrightofroot2infirstcallandoppositeinsecondcall.

}

PrintallnodesatdistancekfromagivennodeGeeksforGeeks
http://www.geeksforgeeks.org/printnodesdistancekgivennodebinarytree/

voidprintkdistanceNodeDown(node*root,intk)
{
if(root==NULL||k<0)return

if(k==0)//Ifwereachakdistantnode,printit
{
cout<<root>data<<endl
return
}
printkdistanceNodeDown(root>left,k1)
printkdistanceNodeDown(root>right,k1)
}

//Printsallnodesatdistancekfromagiventargetnode.
//Thekdistantnodesmaybeupwardordownward.Thisfunction
//Returnsdistanceofrootfromtargetnode,itreturns1iftarget
//nodeisnotpresentintreerootedwithroot.

intprintkdistanceNode(node*root,node*target,intk)
{
//BaseCase1:Iftreeisempty,return1
if(root==NULL)return1

//Iftargetissameasroot.Usethedownwardfunctiontoprintallnodesatdistancekinsubtreerootedwith
targetorroot
if(root==target)
{
printkdistanceNodeDown(root,k)
return0
}
intdl=printkdistanceNode(root>left,target,k)

//Checkiftargetnodewasfoundinleftsubtree
if(dl!=1)
{
//Ifrootisatdistancekfromtarget,printroot
//NotethatdlisDistanceofroot'sleftchildfromtarget
if(dl+1==k)
cout<<root>data<<endl

file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 5/16
7/3/2017 treepreorder.htm

//Elsegotorightsubtreeandprintallkdl2distantnodes
//Notethattherightchildis2edgesawayfromleftchild
else
printkdistanceNodeDown(root>right,kdl2)

//Add1tothedistanceandreturnvalueforparentcalls
return1+dl
}
//MIRROROFABOVECODEFORRIGHTSUBTREE
//Notethatwereachhereonlywhennodewasnotfoundinleftsubtree
intdr=printkdistanceNode(root>right,target,k)
if(dr!=1)
{
if(dr+1==k)
cout<<root>data<<endl
else
printkdistanceNodeDown(root>left,kdr2)
return1+dr
}

//Iftargetwasneitherpresentinleftnorinrightsubtree
return1
}

PrintallnodesthatareatdistancekfromaleafnodeGeeksforGeeks
http://www.geeksforgeeks.org/printnodesdistancekleafnode/
/*Thisfunctionprintsallnodesthataredistancekfromaleafnode
path[]>Storeancestorsofanode
visited[]>Storestrueifanodeisprintedasoutput.Anodemaybek
distanceawayfrommanyleaves,wewanttoprintitonce*/

voidkDistantFromLeafUtil(Node*node,intpath[],boolvisited[],
intpathLen,intk)
{
if(node==NULL)return

/*appendthisNodetothepatharray*/
path[pathLen]=node>key
visited[pathLen]=false
pathLen++

/*it'saleaf,soprinttheancestoratdistancekonlyiftheancestorisnotalreadyprinted*/

if(node>left==NULL&&node>right==NULL&&
pathLenk1>=0&&visited[pathLenk1]==false)
{
cout<<path[pathLenk1]<<""
visited[pathLenk1]=true
return
}

/*Ifnotleafnode,recurforleftandrightsubtrees*/
kDistantFromLeafUtil(node>left,path,visited,pathLen,k)
kDistantFromLeafUtil(node>right,path,visited,pathLen,k)
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 6/16
7/3/2017 treepreorder.htm

}

/*Givenabinarytreeandanuberk,printallnodesthatarekdistantfromaleaf*/
voidprintKDistantfromLeaf(Node*node,intk)
{
intpath[MAX_HEIGHT]
boolvisited[MAX_HEIGHT]={false}
kDistantFromLeafUtil(node,path,visited,0,k)
}



ConvertagivenBinaryTreetoDoublyLinkedList|Set3GeeksforGeeks
http://www.geeksforgeeks.org/convertgivenbinarytreedoublylinkedlistset3/
voidBinaryTree2DoubleLinkedList(node*root,node**head)
{
if(root==NULL)return

//InitializepreviouslyvisitednodeasNULL.Thisisstaticsothatthesamevalueisaccessibleinallrecursive
calls
staticnode*prev=NULL

//Recursivelyconvertleftsubtree
BinaryTree2DoubleLinkedList(root>left,head)

//Nowconvertthisnode
if(prev==NULL)
*head=root
else
{
root>left=prev
prev>right=root
}
prev=root

//Finallyconvertrightsubtree
BinaryTree2DoubleLinkedList(root>right,head)
}


SumofallthenumbersthatareformedfromroottoleafpathsGeeksforGeeks
http://www.geeksforgeeks.org/sumnumbersformedrootleafpaths/

inttreePathsSumUtil(structnode*root,intval)
{
if(root==NULL)return0
//Updateval
val=(val*10+root>data)

//ifcurrentnodeisleaf,returnthecurrentvalueofval
if(root>left==NULL&&root>right==NULL)
returnval

//recursumofvaluesforleftandrightsubtree
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 7/16
7/3/2017 treepreorder.htm

returntreePathsSumUtil(root>left,val)+
treePathsSumUtil(root>right,val)
}

//AwrapperfunctionovertreePathsSumUtil()
inttreePathsSum(structnode*root)
{
//Passtheinitialvalueas0asthereisnothingaboveroot
returntreePathsSumUtil(root,0)
}


ExtractLeavesofaBinaryTreeinaDoublyLinkedListGeeksforGeeks
http://www.geeksforgeeks.org/connectleavesdoublylinkedlist/

structNode*extractLeafList(structNode*root,structNode**head_ref)
{
if(root==NULL)returnNULL

if(root>left==NULL&&root>right==NULL)
{
root>right=*head_ref
//Thisnodeisgoingtobeaddedtodoublylinkedl
listofleaves,setrightpointerofthisnodeaspprevioushead
ofDLL.Wedon'tneedtosetleftpointerasleftisalreadyNULL

if(*head_ref!=NULL)(*head_ref)>left=root
//Changeleftpointerofprevioushead

*head_ref=root
//Changeheadoflinkedlist
returnNULL//Returnnewroot
}

//Recurforrightandleftsubtrees
root>right=extractLeafList(root>right,head_ref)
root>left=extractLeafList(root>left,head_ref)

returnroot
}


DifferencebetweensumsofoddlevelandevenlevelnodesofaBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/differencebetweensumsofoddandevenlevels/

intgetLevelDiff(structnode*root)
{
if(root==NULL)
return0

//Differenceforrootisroot'sdatadifferencefor
//leftsubtreedifferenceforrightsubtree
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 8/16
7/3/2017 treepreorder.htm

returnroot>datagetLevelDiff(root>left)
getLevelDiff(root>right)
}


TreeIsomorphismProblemGeeksforGeeks
http://www.geeksforgeeks.org/treeisomorphismproblem/

boolisIsomorphic(node*n1,node*n2)
{
//BothrootsareNULL,treesisomorphicbydefinition
if(n1==NULL&&n2==NULL)
returntrue

//Exactlyoneofthen1andn2isNULL,treesnotisomorphic
if(n1==NULL||n2==NULL)
returnfalse

if(n1>data!=n2>data)
returnfalse

/Therearetwopossiblecasesforn1andn2tobeisomorphic
//Case1:ThesubtreesrootedatthesenodeshaveNOTbeen"Flipped".
//Bothofthesesubtreeshavetobeisomorphic,hencethe&&
//Case2:Thesubtreesrootedatthesenodeshavebeen"Flipped"
return
(isIsomorphic(n1>left,n2>left)&&isIsomorphic(n1>right,n2>right))||
(isIsomorphic(n1>left,n2>right)&&isIsomorphic(n1>right,n2>left))
}
.



ConstructSpecialBinaryTreefromgivenInordertraversalGeeksforGeeks
http://www.geeksforgeeks.org/constructbinarytreefrominordertraversal/

structnode*buildTree(intinorder[],intstart,intend)
{
if(start>end)
returnNULL

/*FindindexofthemaximumelementfromBinaryTree*/
inti=max(inorder,start,end)

/*Pickthemaximumvalueandmakeitroot*/
structnode*root=newNode(inorder[i])

/*Ifthisistheonlyelementininorder[start..end],thenreturnit*/
if(start==end)
returnroot

/*UsingindexinInordertraversal,constructleftandrightsubtress*/
root>left=buildTree(inorder,start,i1)
root>right=buildTree(inorder,i+1,end)
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 9/16
7/3/2017 treepreorder.htm


returnroot
}


Checkifabinarytreeissubtreeofanotherbinarytree|Set1GeeksforGeeks
http://www.geeksforgeeks.org/checkifabinarytreeissubtreeofanotherbinarytree/

boolareIdentical(structnode*root1,structnode*root2)
{
/*basecases*/
if(root1==NULL&&root2==NULL)
returntrue

if(root1==NULL||root2==NULL)
returnfalse

/*Checkifthedataofbothrootsissameanddataofleftandrightsubtreesarealsosame*/
return(root1>data==root2>data&&
areIdentical(root1>left,root2>left)&&
areIdentical(root1>right,root2>right))
}


/*ThisfunctionreturnstrueifSisasubtreeofT,otherwisefalse*/
boolisSubtree(structnode*T,structnode*S)
{
/*basecases*/
if(S==NULL)
returntrue

if(T==NULL)
returnfalse

/*Checkthetreewithrootascurrentnode*/
if(areIdentical(T,S))
returntrue

/*Ifthetreewithrootascurrentnodedoesn'tmatchthen
tryleftandrightsubtreesonebyone*/
returnisSubtree(T>left,S)||
isSubtree(T>right,S)
}


PrintAncestorsofagivennodeinBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/printancestorsofagivennodeinbinarytree/

boolprintAncestors(structnode*root,inttarget)
{
/*basecases*/
if(root==NULL)
returnfalse

file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 10/16
7/3/2017 treepreorder.htm

if(root>data==target)
returntrue

/*Iftargetispresentineitherleftorrightsubtreeofthisnode,
thenprintthisnode*/
if(printAncestors(root>left,target)||
printAncestors(root>right,target))
{
cout<<root>data<<""
returntrue
}

/*Elsereturnfalse*/
returnfalse
}
GetLevelofanodeinaBinaryTreeGeeksforGeeks
http://www.geeksforgeeks.org/getlevelofanodeinabinarytree/

/*Returnslevelofgivendatavalue*/
intgetLevel(structnode*node,intdata)
{
returngetLevelUtil(node,data,1)
}

intgetLevelUtil(structnode*node,intdata,intlevel)
{
if(node==NULL)
return0

if(node>data==data)
returnlevel

intdownlevel=getLevelUtil(node>left,data,level+1)
if(downlevel!=0)
returndownlevel

downlevel=getLevelUtil(node>right,data,level+1)
returndownlevel
}

PrintnodesatkdistancefromrootGeeksforGeeks
http://www.geeksforgeeks.org/printnodesatkdistancefromroot/

voidprintKDistant(node*root,intk)
{
if(root==NULL)
return
if(k==0)
{
printf("%d",root>data)
return
}
else
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 11/16
7/3/2017 treepreorder.htm

{
printKDistant(root>left,k1)
printKDistant(root>right,k1)
}
}

FoldableBinaryTreesGeeksforGeeks
http://www.geeksforgeeks.org/foldablebinarytrees/

boolIsFoldable(structnode*root)
{
if(root==NULL)
{returntrue}

returnIsFoldableUtil(root>left,root>right)
}

/*Autilityfunctionthatchecksiftreeswithrootsasn1andn2
aremirrorofeachother*/
boolIsFoldableUtil(structnode*n1,structnode*n2)
{
/*IfbothleftandrightsubtreesareNULL,
thenreturntrue*/
if(n1==NULL&&n2==NULL)
{returntrue}

/*IfoneofthetreesisNULLandotherisnot,
thenreturnfalse*/
if(n1==NULL||n2==NULL)
{returnfalse}

/*Otherwisecheckifleftandrightsubtreesaremirrorsof
theircounterparts*/
returnIsFoldableUtil(n1>left,n2>right)&&
IsFoldableUtil(n1>right,n2>left)
}


MaximumwidthofabinarytreeGeeksforGeeks
http://www.geeksforgeeks.org/maximumwidthofabinarytree/

voidgetMaxWidthRecur(structnode*root,intcount[],intlevel)

/*Functiontogetthemaximumwidthofabinarytree*/
intgetMaxWidth(structnode*root)
{
intwidth
inth=height(root)

//Createanarraythatwillstorecountofnodesateachlevel
int*count=(int*)calloc(sizeof(int),h)

intlevel=0

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

//Fillthecountarrayusingpreordertraversal
getMaxWidthRecur(root,count,level)

//Returnthemaximumvaluefromcountarray
returngetMax(count,h)
}

//Afunctionthatfillscountarraywithcountofnodesatevery
//levelofgivenbinarytree
voidgetMaxWidthRecur(structnode*root,intcount[],intlevel)
{
if(root)
{
count[level]++
getMaxWidthRecur(root>left,count,level+1)
getMaxWidthRecur(root>right,count,level+1)
}
}


Givenabinarytree,printallroottoleafpathsGeeksforGeeks
http://www.geeksforgeeks.org/givenabinarytreeprintallroottoleafpaths/

voidprintPaths(structnode*node)
{
intpath[1000]
printPathsRecur(node,path,0)
}

/*Recursivehelperfunctiongivenanode,andanarraycontaining
thepathfromtherootnodeuptobutnotincludingthisnode,printoutalltherootleafpaths.*/

voidprintPathsRecur(structnode*node,intpath[],intpathLen)
{
if(node==NULL)
return

/*appendthisnodetothepatharray*/
path[pathLen]=node>data
pathLen++

/*it'saleaf,soprintthepaththatledtohere*/
if(node>left==NULL&&node>right==NULL)
{
printArray(path,pathLen)
}
else
{
/*otherwisetrybothsubtrees*/
printPathsRecur(node>left,path,pathLen)
printPathsRecur(node>right,path,pathLen)
}
}

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

voidprintRootToleafPaths(Node*node,vector<int>path)
{
//basecase
if(node==nullptr)
return

//includecurrentnodetopathvector
path.push_back(node>data)

//ifleafnodeisfound,printthepath
if(isLeaf(node))
{
for(intdata:path)
cout<<data<<""
cout<<endl
}

//recurseforleftandrightsubtree
printRootToleafPaths(node>left,path)
printRootToleafPaths(node>right,path)
}

//Mainfunctiontoprintpathsfromrootnodetoeveryleafnode
voidprintRootToleafPaths(Node*node)
{
//vectortostoreroottoleafpath
vector<int>path

printRootToleafPaths(node,path)
}
http://www.techiedelight.com/printallpathsfromroottoleafnodesbinarytree/

ConstructTreefromgivenInorderandPreordertraversalsGeeksforGeeks
http://www.geeksforgeeks.org/constructtreefromgiveninorderandpreordertraversal/

Algorithm:buildTree()
1)PickanelementfromPreorder.IncrementaPreorderIndexVariable(preIndexinbelowcode)topicknext
elementinnextrecursivecall.
2)CreateanewtreenodetNodewiththedataaspickedelement.
3)FindthepickedelementsindexinInorder.LettheindexbeinIndex.
4)CallbuildTreeforelementsbeforeinIndexandmakethebuilttreeasleftsubtreeoftNode.
5)CallbuildTreeforelementsafterinIndexandmakethebuilttreeasrightsubtreeoftNode.
6)returntNode.

RoottoleafpathsumequaltoagivennumberGeeksforGeeks
http://www.geeksforgeeks.org/roottoleafpathsumequaltoagivennumber/

boolhasPathSum(structnode*node,intsum)
{
/*returntrueifwerunoutoftreeandsum==0*/
if(node==NULL)
{
return(sum==0)
}

else
{
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 14/16
7/3/2017 treepreorder.htm

boolans=0

/*otherwisecheckbothsubtrees*/
intsubSum=sumnode>data

/*Ifwereachaleafnodeandsumbecomes0thenreturntrue*/
if(subSum==0&&node>left==NULL&&node>right==NULL)
return1

if(node>left)
ans=ans||hasPathSum(node>left,subSum)
if(node>right)
ans=ans||hasPathSum(node>right,subSum)

returnans
}
}

ProgramtocountleafnodesinabinarytreeGeeksforGeeks
http://www.geeksforgeeks.org/writeacprogramtogetcountofleafnodesinabinarytree/
unsignedintgetLeafCount(structnode*node)
{
if(node==NULL)
return0
if(node>left==NULL&&node>right==NULL)
return1
else
returngetLeafCount(node>left)+
getLeafCount(node>right)
}

Determineifbinarytreecanbeconvertedtoanotherbydoinganynumberofswapsofleftandrightchild
http://www.techiedelight.com/determinebinarytreecanconvertedanothernumberswapsleftrightchild/
boolequal(Node*X,Node*Y)
{
//basecase:bothtreesaresame
//(handlesthecasewhenbothtreesareempty)
if(X==Y)
returntrue

return(X&&Y)&&(X>data==Y>data)&&
((equal(X>left,Y>left)&&equal(X>right,Y>right))||
(equal(X>right,Y>left)&&equal(X>left,Y>right)))

}


LongestconsecutivesequenceinBinarytreeGeeksforGeeks
http://www.geeksforgeeks.org/longestconsecutivesequencebinarytree/

voidlongestConsecutiveUtil(Node*root,intcurLength,
intexpected,int&res)
{
if(root==NULL)
file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 15/16
7/3/2017 treepreorder.htm

return

/ifrootdatahasonemorethanitsparent
//thenincreasecurrentlength
if(root>data==expected)
curLength++
else
curLength=1

/updatethemaximumbycurrentlength
res=max(res,curLength)

/recursivelycallleftandrightsubtreewith
/expectedvalue1morethanrootdata
longestConsecutiveUtil(root>left,curLength,
root>data+1,res)
longestConsecutiveUtil(root>right,curLength,
root>data+1,res)
}

/methodreturnslengthoflongestconsecutive
/sequencerootedatnoderoot
intlongestConsecutive(Node*root)
{
if(root==NULL)
return0

intres=0

//callutilitymethodwithcurrentlength0
longestConsecutiveUtil(root,0,root>data,res)

returnres
}

file:///C:/Users/akash/Desktop/placement%20docs/treepreorder.htm 16/16

You might also like