Free Essay

Geeks

In: Computers and Technology

Submitted By shubhtibrewal
Words 1430
Pages 6
GeeksforGeeks
A computer science portal for geeks

GeeksQuiz
Login Home Algorithms DS GATE Interview Corner Q&A C C++ Java Books Contribute Ask a Q About Array Bit Magic C/C++ Articles GFacts Linked List MCQ Misc Output String Tree Graph

A program to check if a binary tree is BST or not
A binary search tree (BST) is a node based binary tree data structure which has the following properties. • The left subtree of a node contains only nodes with keys less than the node’s key. • The right subtree of a node contains only nodes with keys greater than the node’s key. • Both the left and right subtrees must also be binary search trees. From the above properties it naturally follows that:

• Each node (item in the tree) has a distinct key.

METHOD 1 (Simple but Wrong) Following is a simple program. For each node, check if left node of it is smaller than the node and right node of it is greater than the node. itiBTsrc nd*nd) n sS(tut oe oe { i (oe= NL) f nd = UL rtr 1 eun ; / flei lf i >ta nd * * as f et s hn oe / i (oe>et! NL & nd-lf-dt >nd-dt) f nd-lf = UL & oe>et>aa oe>aa rtr 0 eun ; / flei rgti ih ! NL & nd-rgt>aaih-dt oe>aa rtr 0 eun ; / flei,rcriey telf o rgti ntaBT* * as f eusvl, h et r ih s o S / i (iBTnd-lf)| !sS(oe>ih) f !sS(oe>et | iBTnd-rgt) rtr 0 eun ; / psigalta,i' aBT* * asn l ht ts S / rtr 1 eun ;

}

This approach is wrong as this will return true for below binary tree (and below tree is not a BST because 4 is in left subtree of 3)

METHOD 2 (Correct but not efficient) For each node, check if max value in left subtree is smaller than the node and min value in right subtree greater than the node. / Rtrstu i abnr te i abnr sac te * * eun re f iay re s iay erh re / itiBTsrc nd*nd) n sS(tut oe oe { i (oe= NL) f nd = UL rtr(re; euntu) / flei temxo telf i >ta u * * as f h a f h et s hn s / i (oe>et=UL& mxau(oe>et >nd-dt) f nd-lf!NL & aVlend-lf) oe>aa rtr(as) eunfle; / flei temno tergti < ta u * * as f h i f h ih s = hn s / i (oe>ih!NL & mnau(oe>ih)aa rtr(as) eunfle; / flei,rcriey telf o rgti ntaBT* * as f eusvl, h et r ih s o S / i (iBTnd-lf)| !sS(oe>ih) f !sS(oe>et | iBTnd-rgt) rtr(as) eunfle; / psigalta,i' aBT* * asn l ht ts S / rtr(re; euntu)

}

It is assumed that you have helper functions minValue() and maxValue() that return the min or max int value from a non-empty tree

METHOD 3 (Correct and Efficient) Method 2 above runs slowly since it traverses over some parts of the tree many times. A better solution looks at each node only once. The trick is to write a utility helper function isBSTUtil(struct node* node, int min, int max) that traverses down the tree keeping track of the narrowing min and max allowed values as it goes, looking at each node only once. The initial values for min and max should be INT_MIN and INT_MAX — they narrow from there.
/ Rtrstu i tegvnte i abnr sac te * eun re f h ie re s iay erh re (fiin vrin.* efcet eso) / itiBTsrc nd*nd) n sS(tut oe oe { rtr(sSUi(oe ITMN ITMX) euniBTtlnd, N_I, N_A); } / Rtrstu i tegvnte i aBTadis * eun re f h ie re s S n t

vle ae> mnad< mx * aus r = i n = a. / itiBTtlsrc nd*nd,itmn itmx n sSUi(tut oe oe n i, n a)

Implementation: #nld icue sdoh #nld #nld / Abnr te nd hsdt,pitrt lf cid * iay re oe a aa one o et hl adapitrt rgtcid* n one o ih hl / src nd tut oe { itdt; n aa src nd*lf; tut oe et src nd*rgt tut oe ih; } ; itiBTtlsrc nd*nd,itmn itmx; n sSUi(tut oe oe n i, n a) / Rtrstu i tegvnte i abnr sac te * eun re f h ie re s iay erh re (fiin vrin.* efcet eso) / itiBTsrc nd*nd) n sS(tut oe oe { rtr(sSUi(oe ITMN ITMX) euniBTtlnd, N_I, N_A); } / Rtrstu i tegvnte i aBTadis * eun re f h ie re s S n t vle ae> mnad< mx * aus r = i n = a. / itiBTtlsrc nd*nd,itmn itmx n sSUi(tut oe oe n i, n a) { / a epyte i BT* * n mt re s S / i (oe=UL f nd=NL) rtr 1 eun ; / flei ti nd voae temnmxcntan * * as f hs oe ilts h i/a osrit / i (oe>aamx f nd-dt i | oe>aa a) rtr 0 eun ; / ohriecektesbre rcriey * tews hc h utes eusvl, tgtnn temno mxcntan * iheig h i r a osrit / rtr eun iBTtlnd-lf,mn nd-dt-)& / Alwol dsic vle sSUi(oe>et i, oe>aa1 & / lo ny itnt aus iBTtlnd-rgt nd-dt+,mx; / Alwol dsic vle sSUi(oe>ih, oe>aa1 a) / lo ny itnt aus

}

/ Hle fnto ta alctsanwnd wt te * epr ucin ht loae e oe ih h gvndt adNL lf adrgtpitr.* ie aa n UL et n ih ones / src nd*nwoeitdt) tut oe eNd(n aa { src nd*nd =(tutnd* tut oe oe src oe) mlo(iefsrc nd); alcszo(tut oe)

nd-dt =dt; oe>aa aa nd-lf =NL; oe>et UL nd-rgt=NL; oe>ih UL } rtr(oe; eunnd)

/ Die pormt ts aoefntos/ * rvr rga o et bv ucin* itmi( n an) { src nd *ot=nwoe4; tut oe ro eNd() ro-lf ot>et =nwoe2; eNd() ro-rgt ot>ih =nwoe5; eNd() ro-lf-lf =nwoe1; ot>et>et eNd() ro-lf-rgt=nwoe3; ot>et>ih eNd() i(sS(ot) fiBTro) pit(I BT) rnf"s S"; es le pit(NtaBT) rnf"o S"; gthr) eca(; rtr 0 eun ;

}

Time Complexity: O(n) Auxiliary Space : O(1) if Function Call Stack size is not considered, otherwise O(n) METHOD 4(Using In-Order Traversal) Thanks to LJW489 for suggesting this method. 1) Do In-Order Traversal of the given tree and store the result in a temp array. 3) Check if the temp array is sorted in ascending order, if it is, then the tree is BST. Time Complexity: O(n) We can avoid the use of Auxiliary Array. While doing In-Order traversal, we can keep track of previously visited node. If the value of the currently visited node is less than the previous value, then tree is not BST. Thanks to ygos for this space optimization. bo iBTsrc nd*ro) ol sS(tut oe ot { sai src nd *rv=NL; ttc tut oe pe UL / taes tete i iodrfsinadke tako pe nd / rvre h re n nre aho n ep rc f rv oe i (ot f ro) { i (iBTro-lf) f !sS(ot>et) rtr fle eun as; / Alw ol dsic vle nds / los ny itnt aud oe i (rv! NL & ro-dt < pe-dt) f pe = UL & ot>aa = rv>aa

rtr fle eun as; pe =ro; rv ot } } rtr iBTro-rgt; eun sS(ot>ih)

rtr tu; eun re

The use of static variable can also be avoided by using reference to prev node as a parameter (Similar to this post). Sources: http://en.wikipedia.org/wiki/Binary_search_tree http://cslibrary.stanford.edu/110/BinaryTrees.html Please write comments if you find any bug in the above programs/algorithms or other ways to solve the same problem.

Related Topics:
Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method) Print Right View of a Binary Tree Red-Black Tree | Set 3 (Delete) Construct a tree from Inorder and Level order traversals Print all nodes at distance k from a given node Print a Binary Tree in Vertical Order | Set 1 Interval Tree Check if a given Binary Tree is height balanced like a Red-Black Tree
Like 23 Tw eet 3 5

Writing code in comment? Please use ideone.com and share the link here.
137 Comments
Sort by Newest

GeeksforGeeks

harsh tibrewal
Share Favorite

Join the discussion… bakshi_993 •

4 days ago

can you please explain me the use of passing INT_MIN , INT_MAX in isBSTUtil
• Reply • Share ›

Programmer



9 days ago

Similar Documents

Premium Essay

To Geek or Not to Geek?

...Back in the day when people thought of geeks, the first thing to come to their mind was the computer geek who wore the high waist pants with the button up shirt and pocket protector. These people were the ones that were picked on in high school, the ones that were asked to fix your computer if it broke, and typically weren’t considered handy in any other aspect of life. But what exactly is a geek and who is considered a geek in today’s day and age? Is it still a stigmatism to be considered a geek? And what makes a geek any different then, let’s say, a nerd? So what exactly is a geek? According to a typical google search of the word geek you are assigned a label of someone who is an unfashionable or a socially awkward person who is generally only obsessed with computers. But is that really all it is? If a geek is just someone who is obsessed with computers, then wouldn’t that mean anyone who is obsessed with a particular subject technically a geek also? The short answer is yes, yes they are. Geeks are considered people who know a great deal in a particular subject, whether it be computers, games, or even the more “manly” aspects of life, like sports and cars. Yes you can be considered a geek when you are into cars! A geek will explain to you every aspect of the thing they are into to the letter if you ask them about that particular subject. A geek can both be knowledgeable in one area or a jack-of-all-geeks and know a lot about multiple subjects instead. So with all that being...

Words: 877 - Pages: 4

Free Essay

Geek Squad

...Question 1) STRENGTHS * Organisational Culture One prominent characteristic of the Geek Squad that can be identified from the video case is its clear organisational culture. From the old-school uniforms to the pin-up ties, the geek mobile to the identity inspector badges, the founder Robert Stephens fostered a corporate culture of fun. Armed with this ideology, Stephens managed to galvanise the job scope, making a typically monotonous task of repairing computer electronics more enjoyable for both his employees as well as the consumer. The glorified role of a Geek special agent allows employees to feel better about their jobs and themselves, obtaining a higher sense of accomplishment for playing a role in the overall company direction. This could also increase the loyalty of customers where they experience first-hand contact with a Geek Squad ‘Agents’, who were all ensured by the firm to be ‘well-liked’ and ‘socially interactive’. With a strong organisational culture, the Geek Squad would also be able to cultivate a sense unity among its employees who may come from various backgrounds and demographics. A shared culture would promote more communication and understanding as well as reduce conflict or any employee being left out. This would place the company in good stead in dealing with any future challenges. * Customer Service Focus The Geek Squad does not only place importance in the actual repair job, but the whole customer experience as well. According to him...

Words: 1168 - Pages: 5

Premium Essay

Geek Squad

...Robert Stephens to start the Geek Squad? The many changes in the environment that occurred were related to technology, computers, software, communications, entertainment, and social factors such as demographics and cultures, all things he came to realize during his consulting years. While Stephens was attending college and working towards earning a degree in computer science, he also worked as a consultant repairing televisions, computers, and several other items; however his main focus was computers. Through his consulting experience, he came to realize that most people needed help with technology, such as, how it works, its operating system, how to install software, and especially how to read and understand the manuals. 2) What changes in the purchasing patterns of (a) all consumers and (b) woman made the acquisition of Geek Squad particularly important for Best Buy? Changes in social factors such as demographics and culture helped make Geek Squad very popular. In the past, many manufacturers and retailers focused primarily on men. However, they found that woman were becoming increasingly more and more interested in the personal computing and home entertainment. Best Buy’s consumer research began indicating that woman will more than likely outspend men in the near future. Furthermore, Best Buy’s consumer research has proven that women tend to expect personal service during the purchasing and installation after the purchase, just what the Geek Squad is designed to provide...

Words: 852 - Pages: 4

Premium Essay

Geek Squad

...Case Assignment week #2 The Creation of Geek Squad Technology has made communication easier and quicker while at home and while out running errands. It is constantly and persistently changing and advancing around us every day. The first key environmental factor that created an opportunity for Robert Stephens to start the Geek Squad was realizing that being attempted to stay aware of the numerous environmental changes has brought on chaos and will proceed so as long there is innovation, “particularly those related to computers, technology, software, communication, and entertainment” (Kerin, 85). Many consumers had trouble and found it hard installing, operating, and using electronic products. Some of them complains that it takes time to read the manuals. However, that being the second key environmental factor, Robert Stephens, founder of the technology support company Greek Squad, came up with the solution: “I’m going to save you that time because I stay home on Saturday nights and read them for you” (85). Stephens gave up on everything that he has gained, such as an Art Institute scholarship looking forward to get his degree in Computer Science. While student he took a part time job for a research laboratory and began repairing televisions, computers, and a variety of other items. He realized that most people needed some sort of technologic help and that “they saw value in a service whose employees would show up at a specified time, be friendly, use understandable language...

Words: 1224 - Pages: 5

Premium Essay

Geek Squad

...In 1994, Robert Stephens, was a computer science college dropout that founded Geek Squad with $200 and a bicycle in Minneapolis, Minnesota. Dressed in white button-down shirts, too-short black pants, white socks and clip on ties, Geek Squad technicians (known as Agents) repaired computers in local businesses and in customer homes. Stephens had the idea that pulling up on a bicycle dressed like a “geek” would inspire a weird confidence in his computer repair skills. It did. Eight years later, Geek Squad was acquired by Best Buy for an undisclosed amount. Today, Geek Squad is comprised of over 20,000 highly skilled and specially trained computing Agents, home entertainment installers (GSI), Autotechs and appliance repair technicians (GSR’s) located in all U.S. Best Buy stores, at Geek Squad stand-alone locations as well as at service centers located nationwide. Geek Squad provides residential and commercial product repair, support, and installation services both in store and on site. Best Buy acquired Geek Squad to help develop a technological support system for its customers. At the time of acquisition, Best Buy sold computers but didn’t have an effective way to service them. It’s one thing to know the difference between two computers, but another to be able to effectively diagnose a wide range of problems and have the required parts to do so. This related acquisition allowed Best Buy and Geek Squad customers to get a premium level of customer service for their technology...

Words: 558 - Pages: 3

Free Essay

Geek Squad Case Study

...We’ve all heard the name Geek Squad before. Most of us know what they do, maybe some have even taken advantage of the services they offer, but how did it get to be the household name it is today? Founder of the company, Robert Stephens, was, like all entrepreneurs, faced with an abundance of challenges before and after starting his business. Stephens was also given a great opportunity with the beginning of a trend toward personal computers when he started his business. In fact, Geek Squad had become so successful that it was brought to the attention of Best Buy, which purchased the company from Stephens in 2002 to combat some issues they thought that Geek Squad would be able to fix for them. Although they have been extremely successful up to this point, Geek Squad will need to stay ahead of the game to continue to do so, with the rapidly growing and ever changing technological world. When Robert Stephens was studying computer science, he also worked fixing computers for a research laboratory, and started consulting as well. While consulting he realized that most people needed help using and/or fixing their personal computer. In 1994 when Stephens started the company, it was in high demand because of the increase in the use of the personal computer (PC). The people not only wanted someone to help with their computer problems, but also be on time and help them understand what the problem really is, all while being friendly. When Best Buy purchased Geek Squad in 2002 for $3 million...

Words: 750 - Pages: 3

Premium Essay

America Needs Its Nerds

...Leonid Fridman, in his essay, “America Needs Its Nerds,” asserts his disgusted feelings towards the incorrect behavior to Americas intellectually curious “nerds” ( Fridman 3). Fridman’s purpose is to inform americans that we should value “nerds and geeks” (Fridman 29), instead of “athletes [being ] idolized” (Fridman 18). He adopts a disgusted and exaggerated tone in order to persuade Americans to change their ways, and shit their values before America falls apart, and for geeks and nerds to accept and stop being ashamed of themselves. Fridman begins his essay by validating the definition of the word “geek” (Fridman 4) from Websters New World Dictionary, and repeating the word throughout his essay. The dictionary defines greek as a “street performer who shocks the public by biting off heads of live chickens” (Fridman 6-7). Not only does Fridman define geek, but he also compares the definition to the way this term is used to call “intellectually curious and academically serious” (Fridman 4-5) Americans. “Nerds” (Fridman 29) and “anti-intellectualism” (Fridman 12) are other repetitive terms throughout Fridman’s essay that are used to establish his point, making his purpose broad. By repeatedly using the derogatory terms in a bitter tone, allows us to see to who he is speaking to, and how his point is emphasized that nerds need to stop being ashamed of themselves. In addition, Fridman ends his argument by placing it into the readers hand asking a rhetorical question towards...

Words: 364 - Pages: 2

Free Essay

Business Plan

...THE GEEK 354 West Walnut Ave. Dalton, GA 30720 (706) 123-1234 www.thegeek.com [pic] | | | |Jeremy Hickman |Georgia Hickman | |CEO |CFO | |123 Tibbs Rd Dalton, GA |123 Tibbs Rd Dalton, GA | |(706)321-4321 |(706)321-4321 | Created April 26, 2013 Prepared by Jeremy Hickman Table of Contents Cover page……………………………….1 Table of Contacts……….……………….2 Executive Summary……………………..3 Description of Business………………….4 Social Responsibility…………………..…5 Vision and Mission Statement………..…5 Assessment of competition………………5 Company Strengths………………………6 SWOT Analysis…………………………..6 Planned Responses……………………….7 Location of Business……………….…….8 Crime Rate Breakdown……………………9 Industry Description………………..……10 Management…………………..…………10 Goals………………………………………12 Product Features and Branding.....……….12 Market Research………………………..…13 Pricing, Advertising, and Promotions…….14 Distribution ………………………………..15 ...

Words: 3707 - Pages: 15

Premium Essay

Summary Of Leonid Fridman America Needs Its Nerds

...Leonid Fridman wrote an essay titled, “America Needs Its Nerds”, in which he described the derogatory terms and meanings that accompany words such as “nerd” and “geek”. I disagree with Fridman’s view on this topic. Though the terms “nerd” and “geek” may have negative connotations, they are not always meant in a negative manner. Also, Fridman states that nerds and geeks “are ostracized but athletes are idolized” (Fridman 1). I do not always think that statement is true either. For example, in the Greencastle School District, there are many students who value schoolwork, and are not “ostracized” for their dedication to school. There are also students who are dedicated to both sports and academics, which is very respectable. I believe that the...

Words: 582 - Pages: 3

Premium Essay

Leonid Fridman's America Needs Its Nerds

...someone is called nerd by their friends it is not considred a big deal, but when a stranger calls another stranger a 'nerd' or a 'geek', it can be seen as agressive. The sole idea of 'America Needs Its Nerds' ny Leonid Fridman is that America does, if fact, need its individuals that would rather stay at home and read a book rather than go out and party, who would rather study than play football, who would rather build upon their academic prowess than their social or physical skills because without kids like these, America; the great, world-class superpower, would be full of sheep who follow the trend of being anti-intellectual who intentionally dumb themselves down to fit in with people who follow the same stupid trends. One of the points that Fridman makes is that people who are a little less socially amble are often called names like 'geek'. A 'geek', Fridman writes, is, according to Websters New World Dictionary, a street performer who shocks the public by biting off heads of live chickens. This fact is especially appaling as Fridman cannot even begin to comtemplate how, and when, America's society reached the point of comparing it's academically advanced individuals to freaks on the street who kill chicken by biting their heads off for others' entertainment. Fridman...

Words: 449 - Pages: 2

Premium Essay

America Needs It's Nerds Rhetorical Analysis

...In “America Needs It’s Nerds” by Leonid fridman uses various persuasive elements in order to convince the audience of his claim that “There is something very wrong with the system of values in a society that only had derogatory terms like nerd and geek for the intellectually curious and academically serious.” The author works with logos, word choice, and calls to action to persuade his readers of his claim. Fridman applies logos by presenting a firm background of the “derogatory” term geek which is often thrown around to described as one who takes on the rigorous pursuit of knowledge. It is written in the text that “A geek according to Webster’s New World Dictionary, is a street performer who shocks the crowds by biting the heads off...

Words: 291 - Pages: 2

Free Essay

Observation

...Nerds With nerds being around so many years over time things are beginning to change in their subculture. Nerds in modern day are not like the use to be back in the days. Everything about them are evolving from lame to the point now you can barely notice them from any other person. They’re just trying to fit in just like any other subculture now days. Nerds are not the same now how they were back then. Everyone calls this subculture by many names mostly Nerds or Geeks. What about the nerds and geeks of the world? Where is their infographic, when will nerds feel safe to leave their studies and work alone and try to live a little? When will geeks leave their parents’ basements and shout they are people too? How about our friends, will they ever stand up straight and be heard or will they be left behind the group of cool kids, plotting their revenge? Infrographics Guy commented “Aw, who cares, geeks and nerds rule or will rule the world when they get older so bow to them now while you still have a chance.” Yes, Nerds are still unpopular but they are coming up in the world. No longer are they basic people with button downs, glasses, and suspenders. The term “nerd” goes back as far as I can remember. The term is not something they like to claim but it’s just a gift that certain humans were born with. Everything about them is evolving, nerds do not dress the same anymore or do they act the same. Nerds are literally smart people and it’s a big correlation in the two. Being smart...

Words: 953 - Pages: 4

Free Essay

Geek

...(http://www.jovago.com/) (http://www.kaymu.co.ke) (https://www.hellofood.co.ke/) (http://www.easytaxi.co.ke/) (http://www.lamudi.co.ke) | | (http://www.jumia.co.ke/) | Fast shipping nationwide WORK WITH JUMIA (HTTP://WWW.JUMIA.CO.KE/JFORCE/)(http://www.jumia.co.ke/jforce/) (http://www.jumia.co.ke/) NEW Take home entertainment to a whole new level with Sony Bravia 101.6 cm (40) KLV-40R452A Full HD LED Television. With technologies like Clear Resolution Enhancer and Motionflow XR 100, this LED TV is a designed to give you the best. Solid Durability With Enhanced Protection Features With X-Protection Pro, you can expect solid durability from your TV. This unique feature enhances protection from humidity, surge, lightning and dust. Its no ventilation hole design and improved coating solution, for example, shield the television from external threats – letting you enjoy crystal clear picture quality that lasts longer. Clearer, More Natural Image Details Immerse yourself in a world of spectacular, crisp moving images with the Clear Resolution Enhancer. Superior noise reduction, together with natural pictures, offers a depth of realism and details to your viewing experience. Balanced Reproduction Of Sound Frequencies Sony's Clear Phase Speakers will pique your listening experience as much as the rich picture details on screen. This technology fine-tunes the speakers' frequency response for smoother, more balanced reproduction of the entire...

Words: 621 - Pages: 3

Premium Essay

The Geeks of Chic

...Caught between Corporate Cultures” by critically discussing the following organizational behavior issues as they pertain in the case: Task 1.1 Critically analyze the leadership approach (es) which Rick Belkner, Mike Wilson and Jack Greely employed in the case. Task 1.2 Critically analyze the power and politics issues evident from the case. Task 1.3 Critically analyze the components of the conflict management process evident from the case. Task 1.4 Critically analyze the organizational culture issues of Consolidated Life. Task 2 Make recommendations: Draw up a table and summarize what improvements are needed in relation to: 1. Leadership and associated change management strategies. 2. Power and politics 3. Conflict management 4. Organizational culture in Consolidated Life 1 ASSIGNMENT Task 1.1 (538 words) I believe that individuals are groomed through experience and exposure to be leaders. Some leaders can influence and motivate those around them more effectively and easily than others and guide them to be a more coherent and cohesive unit in order to accomplish the objectives and targets. All three main characters in this case, exhibit different management styles and approaches which clearly differentiates them as not only managers but also as individuals with a different approach, conditioning and thought process (Zastrow, 2008). Rick clearly displays all the traits of delegative leadership or a Laissez Fare approach to leadership. It is a leadership style...

Words: 2776 - Pages: 12

Premium Essay

Pricing Term Paper

...for business), Buzz (young entertainment enthusiast), Barry (the affluent professional), Jill (the busy suburban mom) and Ray (the tech savvy family man). Store associates are trained to recognize customer segments and stores are stocked with products that appeal to the segments that frequent each individual store. Best buy even established reward zone, a customer reward/appreciation system that rewards customer purchases with gift certificates, discounts and special shopping events. The company offers services for customers such as services plans, installations and in store electronics repairs. Best buy has grown vastly in the past few years, offering 9 other brands within the Best Buy name, such as; Carphone warehouse, Best buy mobile, geek squad,...

Words: 1841 - Pages: 8