The problem:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

 

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

 

My analysis:

The problem is little tricky, but it provoides an very important skill in sovling symmetric problem.
Key: the binary tree is the best instance to explore sysmmetric properity.
Let's think in this way.
The tree A has its mirror B. If A is a sysmmetric tree <==> A and B should be the same.
Apparently, any move on B(left search or right search), it's equal to the oppsite move on A.(B is the mirror image).
Thus we could use a A to emmulate any move on B(just opposite the move).

return helper(cur_root1.left, cur_root2.right) && helper(cur_root1.right, cur_root2.left);

Then, we could use the classic method of testing if two trees are matching, to test on tree A and B(imitate on A).

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
    
        return helper(root, root);
    }
    
    private boolean helper(TreeNode cur_root1, TreeNode cur_root2) {
        
        if (cur_root1 == null && cur_root2 == null)
            return true;
        
        if (cur_root1 == null || cur_root2 == null)
            return false;
        
        if (cur_root1.val != cur_root2.val)
            return false;
        
        return helper(cur_root1.left, cur_root2.right) && helper(cur_root1.right, cur_root2.left);
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-08
  • 2021-10-01
  • 2022-01-05
猜你喜欢
  • 2021-06-23
  • 2021-08-30
  • 2021-11-09
  • 2021-11-29
  • 2021-07-30
  • 2022-03-02
相关资源
相似解决方案