Symmetric Tree

update Jan 1, 2018

LeetCodearrow-up-right

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
    / \
   2   2
  / \ / \
 3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note: Bonus points if you could solve it both recursively and iteratively.

Basic Idea:

对于这道题目,直接考虑对称的情况,左边的左边等于右边的右边,左边的右边等于右边的左边。

思路 1:Iterative 用两个栈分别存放左右两边要比较的node,比较之后按照下一次要比较的顺序将他们的child push 进 stack。

Python Code:

思路 2:Recursive 递归函数接收左右两个node,比较左边的左和右边的右,左边的右和右边的左,然后递归比较。 时间复杂度O(n),因为我们只visit每个node一次。

Java Code: