Description
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:
1 |
1 |
But the following [1,2,2,null,3,null,3]
is not:
1 |
1 |
Note:
Bonus points if you could solve it both recursively and iteratively.
Test Cases
null
root- one root
- complete + symmetric binary tree
- non-complete + symmetric binary tree
Thoughts
Create a helper()
method to check if two symmetric nodes share the same value. It takes in TreeNode n1
and TreeNode n2
as two arguments and return values based on conditions. Note, root node is handled sperately.
- Return
true
ifn1 == null && n2 == null
- Return
false
ifn1 == null || n2 == null
- Return
false
ifn1.val != n2.val
- Return
helper(n1.left, n2.right) && helper(n1.right, n2.left)
Code
1 |
|
Solution above use recursive dfs, the problem can also be solved by iterative dfs with a stack.
Thoughts (iterative dfs)
1 |
// iterative dfs |
Thoughts (iterative bfs)
iterative BFS approah ues queue data structure to process node level by level. This might have a better performance, since it goes level by level, catch unmatch node pair sooner and return false
immediately without going too deep of the tree (like DFS approach).
1 |
// iterative bfs |
[Reference]
近期评论