filmov
tv
Test If A Binary Tree Is Symmetric ('Symmetric Tree' on Leetcode)

Показать описание
📹 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))
++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++
This problem is problem 10.2 in the book Elements of Programming Interviews by Adnan Aziz
Комментарии