101. Symmetric Tree
https://leetcode.com/problems/symmetric-tree/
Problem
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
But the following [1,2,2,null,3,null,3]
is not:
First Approach
My initial approach to this problem is to tackle the tree level by level (breadth-first search) and compare the nodes at each given level. A level is symmetrical if the nodes in the left half (from left to right) are the same and occur in the same order as the reverse of the nodes in the right half (from left to right).
By going level by level, if we find any level to be asymmetrical, then we can deduce that the tree is also asymmetrical. Once we reach the end of the tree without any hiccups, we can safely say that the tree is symmetrical.
Mistake: symmetric around its center
For this question, symmetric around the center actually means given two nodes, their sub-trees are symmetric. For example:
Revised Solution
Starting from scratch, we can still traverse the tree in a similar fashion with a variant of bread-first search / depth traversel. As we process two nodes as a time, we can picture an imaginary line that cuts in-between these two nodes as the CENTER of symmetry and its children are the left and right side (convenient since it's a binary).
As such, we only need to compare two nodes at a time, and verify if the children on one side mirrors the other (reversed). The basic traversel algorithm therefore works as our starting base, and now we just filter two head nodes (Node A and Node B) and compare L1 == R2 and R1 == L2.
The Second Mistake
Had a huge slip-up here, forgetting a fundamental construct of binary search trees. The existence of None / Null. In the above section about my mistake, I erronously added children to the nodes which were None. However, this is impossible, as None cannot have any children - it simply stops there. By missing this slight error, this has caused me a huge headache and I realise now my original interpretation of the question was right - just that I was wrong. In the example given above, the tree actually should look like so:
How to know how many children to expect in the next level? Since each node is binary, the next level will have 2*(number of nodes in current level)
Last updated
Was this helpful?