Data Structures: Binary Search Tree

HackerRank · Beginner ·⚡ Algorithms & Data Structures ·9y ago

Key Takeaways

This video teaches how to detect if a tree is a valid binary search tree, covering the definition of a binary search tree, and providing a solution using a recursive approach with shrinking Min and Max values.

Full Transcript

hi I'm Gail lock McDow author of cracking coding interview today we're going to talk about detecting if a tree is actually a valid binary search tree a binary search tree as you may recall is a binary tree so has a left node and right node but it's one where all the nodes on the left for given node all the nodes on its left are smaller than it and all the nodes on its right are bigger than it so we want to check to make sure binary tree is actually binary search tree and so that means checking to make sure that ordering property is true so one approach that a lot of people take that is actually mistaken is they think okay I'll just walk through my tree and check to make sure for any given node compare it to the left node compare it to the right node and see if it's in the right order so is the left node smaller than the current node and smaller than right and the problem with that is that even if that's true it may not be a valid binary search tree because there could be something something else underneath it that's bigger than the parent so for any given route maybe it's grandchild is actually bigger than it and maybe it's the left grandchild is actually bigger than it so that won't actually work another approach that is correct but slow is we can say okay all the nodes on the left must be smaller than all the nodes on the right so take each node get the biggest node on the left compar it to the to this node get the smallest node on the right compared to that node that'll work but it's pretty inefficient these get min and get Max operations uh require walking through that whole tree so so that's going to actually get very very slow a faster way is we can flip around this logic we can say okay at the very beginning our root is valid we have no the root can be anything in the entire world but when we go to the left we going to walk through all its children and when we go to the left everything on the left has to be between the integer minimum and the root value and everything on the right has to be between the root value and integer maximum okay so now let's go to the left well that you know we'll check to make sure hey is that is that node on the left is that within those values great it is okay keep going now when going go to the right side of that all those values must be between that left nod's value and that root nodes value so we're going to pass around these these ranges of Min and Max and say at every any given point are you within that Min and max range so that's how we tackled this problem okay so what we need for this method actually is we need check BST to take in a Min and max value and this initial node is going to just take in pass an integer Min so initially the root can be any value at all at all actually now I'm going to make sure I'm going to specify here these are inclusive ranges okay so in the very beginning first I want to do so I want to check to make sure my root is in the right value so if it's smaller than my Min or it's bigger than my Max return false um I also want to be careful of I need a base case here so if root is null then return true otherwise go left or right so check my left and right root dot um do left and I'm going to come back to what these ranges are in a second so check the left and check the right if both are valid then it's valid okay that's a basic log now initially my so my root can be any between Min and Max if I go to the left of my root anything down there can still be as small as the Min but it cannot be any bigger than the than the root and in fact it can't even be equal to the root because we actually do not have duplicates in this tree and so the biggest so my values on the left of my root can be anywhere between Min at the smallest and one smaller than the root when I go to the right things can be at least or they have to be at least as big as root actually one bigger and they can be up to that max value now let's run this and see what happens perfect it worked so we can do it so in more test cases if we want but let's remember let's walk through what this does so this basically flips around our initial logic what we're going to do is pass these ever shrinking Min and Max values so the iic is basically root had had to be somewhere between Min and Max if we go to the left we've now shrunken the biggest those values can be they can be between that old minimum and root if we go to the right then they can be still as big as that Max but they can't but they have to be at least as big as root now you want to be very careful on uh any recursive problems to you know pay extra close attention there to the base cases because that's a really really easy thing to mix up one thing I always check for in a recursive problem is if I'm returning a Boolean I definitely want to make sure that I have some sort of return true and some sort of return false statement somewhere because if obviously if I only have a return false statement how would I ever get anything other than false so that's just a quick little sanity check to do okay right so that's that's how we tackle this problem the efficiency of this problem this solution is actually really nice we actually have a linear time solution and we know since we have to touch every single node in the tree we can't do any better than that so this is pretty pretty close to as optimal as we can get and the space complexity by the way of this problem is going to be if it's a balance tree it's going to be log n because of that recursive complexity so now that you've you seen this problem why don't you try either try this again on your own or check out some new binary sech tree problems good luck

Original Description

Learn how to detect if a tree is a valid binary search tree. This video is a part of HackerRank's Cracking The Coding Interview Tutorial with Gayle Laakmann McDowell. http://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview?utm_source=video&utm_medium=youtube&utm_campaign=ctci
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from HackerRank · HackerRank · 30 of 60

1 HackerRank for Professors
HackerRank for Professors
HackerRank
2 Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
HackerRank
3 How to Leverage Data-Driven Insights to Improve Recruiting Results
How to Leverage Data-Driven Insights to Improve Recruiting Results
HackerRank
4 Hire Top Linux Talent and System Admins with SudoRank [Webinar]
Hire Top Linux Talent and System Admins with SudoRank [Webinar]
HackerRank
5 How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
HackerRank
6 Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
HackerRank
7 How to Use HackerRank's CodePair Tool [Tutorial]
How to Use HackerRank's CodePair Tool [Tutorial]
HackerRank
8 Find Linux Talent with SudoRank challenges [Tutorial]
Find Linux Talent with SudoRank challenges [Tutorial]
HackerRank
9 VMware's Mat Connot details his favorite new way to engage top programmers
VMware's Mat Connot details his favorite new way to engage top programmers
HackerRank
10 An Inside Look at Coinbase's Recruiting Strategy [webinar]
An Inside Look at Coinbase's Recruiting Strategy [webinar]
HackerRank
11 How Evernote Enhanced Their Tech Recruiting Process
How Evernote Enhanced Their Tech Recruiting Process
HackerRank
12 5 strategies for being a tech recruiting champion with HackerRank [Webinar]
5 strategies for being a tech recruiting champion with HackerRank [Webinar]
HackerRank
13 HackerRank Story - Lets make the world flat!
HackerRank Story - Lets make the world flat!
HackerRank
14 Data Structures: Hash Tables
Data Structures: Hash Tables
HackerRank
15 Data Structures: Anagram Problem Solution
Data Structures: Anagram Problem Solution
HackerRank
16 Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
HackerRank
17 Big O Notation
Big O Notation
HackerRank
18 Algorithms: Graph Search, DFS and BFS
Algorithms: Graph Search, DFS and BFS
HackerRank
19 Algorithms: Bit Manipulation
Algorithms: Bit Manipulation
HackerRank
20 Data Structures: Solve 'Find the Running Median' Using Heaps
Data Structures: Solve 'Find the Running Median' Using Heaps
HackerRank
21 Data Structures: Heaps
Data Structures: Heaps
HackerRank
22 Algorithms: Memoization and Dynamic Programming
Algorithms: Memoization and Dynamic Programming
HackerRank
23 Algorithms: Sort An Array with Comparator
Algorithms: Sort An Array with Comparator
HackerRank
24 Algorithms: Solve 'Coin Change' Using Memoization and DP
Algorithms: Solve 'Coin Change' Using Memoization and DP
HackerRank
25 Data Structures: Solve 'Contacts' Using Tries
Data Structures: Solve 'Contacts' Using Tries
HackerRank
26 Data Structures: Tries
Data Structures: Tries
HackerRank
27 Algorithms: Bubble Sort
Algorithms: Bubble Sort
HackerRank
28 Algorithms: Merge Sort
Algorithms: Merge Sort
HackerRank
29 Algorithms: Quicksort
Algorithms: Quicksort
HackerRank
Data Structures: Binary Search Tree
Data Structures: Binary Search Tree
HackerRank
31 Data Structures: Trees
Data Structures: Trees
HackerRank
32 Algorithms: Solve 'Shortest Reach' Using BFS
Algorithms: Solve 'Shortest Reach' Using BFS
HackerRank
33 Algorithms: Solve 'Connected Cells' Using DFS
Algorithms: Solve 'Connected Cells' Using DFS
HackerRank
34 Algorithms: Solve 'Recursive Staircase' Using Recursion
Algorithms: Solve 'Recursive Staircase' Using Recursion
HackerRank
35 Algorithms: Binary Search
Algorithms: Binary Search
HackerRank
36 Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
HackerRank
37 Data Structures: Linked Lists
Data Structures: Linked Lists
HackerRank
38 Data Structures: Cycles in a Linked List
Data Structures: Cycles in a Linked List
HackerRank
39 Data Structures: Stacks and Queues
Data Structures: Stacks and Queues
HackerRank
40 Data Structures: Queue With Two Stacks
Data Structures: Queue With Two Stacks
HackerRank
41 Data Structures: Balanced Parentheses in Expression
Data Structures: Balanced Parentheses in Expression
HackerRank
42 Algorithms: Recursion
Algorithms: Recursion
HackerRank
43 How to Hire for Your Startup [Collision Panel Video]
How to Hire for Your Startup [Collision Panel Video]
HackerRank
44 HackerRank main() San Francisco | November 8, 2018
HackerRank main() San Francisco | November 8, 2018
HackerRank
45 The Enterprise Playbook for Technical Hiring
The Enterprise Playbook for Technical Hiring
HackerRank
46 Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
HackerRank
47 Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
HackerRank
48 Building a Culture for Developer Innovation
Building a Culture for Developer Innovation
HackerRank
49 Developer Trends in 2020 and Beyond
Developer Trends in 2020 and Beyond
HackerRank
50 HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank
51 Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
HackerRank
52 Accelerating Developer Innovation at PhonePe with Rahul Chari
Accelerating Developer Innovation at PhonePe with Rahul Chari
HackerRank
53 The Future of Work for Developers
The Future of Work for Developers
HackerRank
54 Scaling AI from Proof of Concept to Production
Scaling AI from Proof of Concept to Production
HackerRank
55 The Secret Sauce to getting hired in Myntra’s Tech Team
The Secret Sauce to getting hired in Myntra’s Tech Team
HackerRank
56 Reimagining Money with Paypal
Reimagining Money with Paypal
HackerRank
57 Engineering Predictions for 2021 and Beyond! 🎬
Engineering Predictions for 2021 and Beyond! 🎬
HackerRank
58 Future-forward Tech & Careers with BNY Mellon
Future-forward Tech & Careers with BNY Mellon
HackerRank
59 How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
HackerRank
60 Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
HackerRank

This video teaches how to validate a binary search tree using a recursive approach with shrinking Min and Max values, and provides tips for solving recursive problems.

Key Takeaways
  1. Define a binary search tree and its properties
  2. Implement a recursive function to validate the tree
  3. Use shrinking Min and Max values to validate each node
  4. Handle base cases for recursive problems
💡 The key to solving this problem is to flip around the initial logic and pass shrinking Min and Max values to each recursive call, ensuring that each node's value is within the valid range.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →