Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Key Takeaways
The video demonstrates how to determine if a binary tree is symmetric using algorithms, specifically the Symmetric Tree problem on Leetcode, utilizing techniques such as recursive and iterative approaches to check for symmetry.
Full Transcript
[Music] all right so it's good to be back we had a good two days off I could not find a place with a whiteboard that was open because it was Christmas and I don't know I'm crazy and I want to do this problem but it is exciting to be back and we have a very cool problem today well I mean cool in the sense that we do these problems to continue to sustain our livelihoods and these are actually kind of boring but test if a binary tree is symmetric so the question is we need to test if a binary tree is symmetrical in its structure and symmetrical in value so if we draw a line down the middle of our tree down straight through the root vertical line will the tree fold on itself and will the values be equivalent so here are examples if we have no that is basically an equivalent tree I mean it is just no but if the root is null of our binary tree then it's symmetrical there's nothing to compare if we just have one node if we draw a line straight through it's still symmetrical and we have a tree like this or root is one we have two and two if we draw a line straight through do you see how they'll fold on each other and those twos are the same and is structurally equivalent and if it's going to have value equivalence it must be structurally equivalent here is an example where things go wrong we see one it's left value is two and his right value is no this is where if we fold the tree on itself we're not going to have equivalent values and just to further this do see it stays symmetrical this stays as a root of two left and right one it stays symmetrical here but where do we fail we stay symmetrical here but right there if we draw a line everything will fold over and work except for the four and the null right there so those will not match for does not will know they're structurally different this is not even a value difference we could put a five there if we put a five there it still fails why because values are not the same these values are not the same if we fold them these are the two values that fold onto each other and they need to be the same and they're not this is why this tree fails so this is the problem test if a binary tree is symmetric a lot of people asked normally when we deal with trees it's recursive but a lot of people have problems were thinking how do I traverse a tree how does this recursion pan out and let me give you an example to show you how you need to think about this problem so that you understand how the recursion and traversal will happen all right so forget about trees forget about recursion forget that okay we're in an interview high-pressure situation let's go back to what we were doing I give you an array tell me if this array is symmetric if we put a cut through the middle if we put a cut through here tell me if this array is symmetric this is kind of like checking if a string is a palindrome so what are you gonna do you're going your eyes your eyes are gonna go here what what are you doing what what are we doing fundamentally we're doing a pair comparison we're comparing pairs are those equivalent yes what's the next pair we go one more inward what's the next pair and then what do we see for design equal three this is not a symmetric array so now what you've establish is you've put that aside it's a tree we need to find symmetric the whether symmetric you put that aside and you get back to what am I really trying to solve what are my points of interest and in recursion every single recursive recursive thing is going to take in points of interest and our points of interest are two values we're going to be doing pair comparisons this is huge because when we're working with the recursion the way we crafted the signature of our recursive function is going to be based on what we're trying to solve what we're interested in we see that we're going to be interested in pair comparison so our recursive function is most certainly at the least going to take in pairs of values so now let's get back to the binary tree and see what pairs we need to compare all right so here let's color code everything here's our example that we were working well a little different from what we were working with before and remember pair comparisons now we're thinking forget the code do this in your head do this by and like how are you going to do this so first off we know the route no matter what a route is symmetric by itself we don't even need to think about peer comparison in a recursive function we could pass the route as both of the two two items being compared because it's going to compare it to itself and it's symmetric so what do we need to compare next let's change color next we know we need to fold these two guys together okay those need to be equivalent but then where do we go from there this is the key thing that's going to craft our function for us so what we need to do is let's this is the left subtree this is the right subtree so this is a left subtree this is a right subtree so the theme the the left value this guy who does he need to be equal to B needs to be equal to him so what does that say fine yeah am I too loud so notice okay it's tough to write recursive functions but let's not even look at the code we haven't even got to code yet what we notice is our left subtree and right subtree we're working with these nodes representing the root of those sub trees we notice the left sub trees left must equal the right sub trees right this is part one now what else do we see we also see that this guy needs to equal this guy so what does that mean that must equal that well what is that let's write another rule well here's rule one here's Rule two so what we need what we need to happen is we need the left subtree so left to equal the right subtrees right we need the left sub trees right to equal the right sub trees left we see that doesn't happen here so this first thing passes but this does not happen think about this this is this is the answer this is what needs to happen this is how the traversal needs to happen our recursive function will take a left subtree and a right subtree it's going to enforce these rules if these rules fail at any point in our traversal it's over the tree is not symmetric if it fails here then we're gonna bubble up the answer that it failed is false so for this guy for this guy he's gonna say is my left and right symmetric he's necessay is my left or right symmetric so let's get into the recursive code and see how the code pants out that now that we've deduced these rules okay all right so here oh all right so here is everything converted to the code nothing has changed all we're doing is converting this to logic everything that we just explained is what we're about to do if the root is null immediately we short-circuit execution we're finished it's a symmetric tree we're done but what we do is if it's not not then we need to go into our recursion and we need to check the left subtree and the right subtree remember back to what we just did okay so now we go into here if the left subtree and right subtree if our nodes are no they are symmetric they are non-existent and we fold correctly to both non-existent positions we return true the check passes for those two subtrees but if they're both not know if they're both not know that we need to check the value and then we need to continue our recursion to the left and rights of the node we are sitting at and we need to continue to check cemetary first we check their values if their values are the same good we're done with these nodes we're holding and then what we need to do is we need to check to make sure that our left sub trees left it's equivalent to our right subtrees right and that our left sub trees right it's equivalent to our right subtrees left so as you can see here left left sub trees left needs to be equal to right subtrees right left sub trees right needs to be equivalent to the right sub trees left so we enforce that we continue our recursion and we return we will bubble up the answer let me save return in a recursive we didn't return our recursive call we know that whatever that recursion will return to us will bubble back up the call stack and return our answer to our top level caller and then finally we return false when would we reach this line first we know that both the nodes are no then we know both those aren't know if one node has a value and one node is no or this note if the left subtree has a value and the right subtree is a null or the right subtree has a value and left subtree is null then we it's impossible to have symmetry because they are structurally different we can not even do a value check and therefore we return false so this is our policy this is our never we define a recursion function to operate on a tree it's as if we're defining a policy that we must enforce through our recursion and through our iteration through the tree so this is gonna bubble its way down it's gonna go down the tree come back up gonna go like that do it's like searching and and go down the tree and do its checks so what would the time and space complexity be so let's really think think about this the time is kind of easy because it's a word I need to check and nodes and we're did check if the tree is symmetric we must check all of the nodes we have n nodes we declare the number of nodes as n so we have all of n time and the time complexity our space complexity why is it all of H or height but during our recursion we are only going to keep up to the height of the tree our call stack is only going to have as many calls as as tall as the tree so when we're going down we're gonna do go like this we're gonna go like this like this or art art the the amount of space we use on the call stack is not proportional to the amount of nodes is proportional to the height of the tree because we're doing a height traversal it doesn't work out exactly to the height but it is proportional to the height and it scales with the height as our input gets large so we're gonna see this in different problems with the space being all of H so it's going to become more familiar with you as we do more problems but could the space be at all of n you know if it's a skew tree could it be where space of n because yes the call stack couldn't go that deep but think about this if if we had a skewed tree it would immediately fail if our tree was skewed like this and we did a comparison like that we would fail on the first comparison it wouldn't really make sense to say that the worst case would be oh well it wouldn't make sense but we would instantly fail our comparisons so in a problem like this why would you even get a skewed tree so if it's o of H is like the more common like it makes a lot more sense than saying o of N worst case because that probably would not even happen it would fail on the first comparison so this is the problem we just walk through how you think about the recursion do not the thing about recursive functions best way to get the signature of your function is to think about what is my policy what must I enforce what do I need to know through every single iteration of this recursion what is each frame need in this problem we need two nodes we we didn't know which nodes initially but we knew we needed to compare pairs we knew we needed compare pairs of something in this problem that turned out to be pairs of sub trees in other problems it could be anything else if we're doing backtracking and it's like the end Queens problem or something maybe we're we need to keep the data of how many placements we've done so it all depends on what your function needs and the more problems you do the more you improve in this so this is this problem if you liked this video hit the like button subscribe to the channel we're trying to do a video every day to improve engineers and the whole point is channel is to empower the software engineer to perform better in the interview know what to expect and perform at their best and that's what this is all about so yeah [Music]
Original Description
Code - https://backtobackswe.com/platform/content/test-if-a-binary-tree-is-symmetric/solutions
Free 5-Day Mini-Course: https://backtobackswe.com
Try Our Full Platform: https://backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions
Question: Write a program to check if a binary tree is symmetric in structure as well as value.
A binary tree is symmetric if we can draw a vertical line down from the root and the left and right subtrees are mirrors of each other in structure and value.
The least this could be is O(n) time because we have to inspect all n nodes values to ensure that they conform to the tree being symmetric.
All we need to do is traverse the tree correctly with our recursion checking pairs for conformity.
The Conditions
If the root is null, the tree is symmetric.
Our checking function will take 2 nodes in to compare for symmetry.
Our Base Cases
If both nodes passed in are null, by default we have a symmetric tree.
If one node is null and the other is not, then we have incongruence, the tree is not symmetric since a pair failed.
If both nodes are null, then compare values. If values are equal, then good. Go left and go right.
How do we come up with this on the spot?
First recognize the base cases.
Then recognize we will need some way to compare pairs of nodes since that's what matters when checking for symmetry.
Even if this were an array that is how we would do it, pairs of indices.
Then recognize the way the recursive case must continue the work on the way down and your solution would look like this at the end.
Complexities
Time: O(n)
Space: O(h) (as we discussed, it can't really be O(n) worst case since
the first check would fail if the tree is skewed. The worst case IS O(h))
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: https://www.youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww
Tuschar Roy: https://www.youtube.com/
Playlist
Uploads from Back To Back SWE · Back To Back SWE · 12 of 60
1
2
3
4
5
6
7
8
9
10
11
▶
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
4 Tips To Learn Java Programming As Fast As Possible As A Beginner
Back To Back SWE
3 Mistakes Beginners Make When First Learning Java and Android Development
Back To Back SWE
How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
Back To Back SWE
The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
Back To Back SWE
Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Back To Back SWE
The N Queens Problem using Backtracking/Recursion - Explained
Back To Back SWE
Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Back To Back SWE
How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
Back To Back SWE
Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Back To Back SWE
The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
Back To Back SWE
The Dutch National Flag Problem (The Quicksort "Band-Aid")
Back To Back SWE
Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Back To Back SWE
The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
Back To Back SWE
How To Permute A String - Generate All Permutations Of A String
Back To Back SWE
The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
Back To Back SWE
Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search - First Occurrence Of Substring
Back To Back SWE
Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Back To Back SWE
Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Back To Back SWE
Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Back To Back SWE
Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Back To Back SWE
Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Back To Back SWE
Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Back To Back SWE
Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Back To Back SWE
Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Back To Back SWE
The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
Back To Back SWE
Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Back To Back SWE
Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Back To Back SWE
Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Back To Back SWE
Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Back To Back SWE
The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
Back To Back SWE
Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Back To Back SWE
Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Back To Back SWE
Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Back To Back SWE
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Back To Back SWE
Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Back To Back SWE
Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Back To Back SWE
Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Back To Back SWE
Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Back To Back SWE
Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Back To Back SWE
Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Back To Back SWE
Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Back To Back SWE
Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Back To Back SWE
What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
Back To Back SWE
An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
Back To Back SWE
Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Back To Back SWE
A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
Back To Back SWE
Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Back To Back SWE
Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Back To Back SWE
All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
Back To Back SWE
Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Back To Back SWE
Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Back To Back SWE
Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Back To Back SWE
Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Back To Back SWE
Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Back To Back SWE
The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
Back To Back SWE
Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Back To Back SWE
Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Back To Back SWE
The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
Back To Back SWE
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Back To Back SWE
Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Back To Back SWE
More on: Algorithm Basics
View skill →
🎓
Tutor Explanation
DeepCamp AI