LeetCode: symmetric-tree判断是否为镜像树

题目描述


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.

confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

思路:1、在判断是否为镜像的时候,如果采用层序遍历就无法确定第二种情况不是镜像树,所以需要去观察镜像的特点,对问题进行分解,发现可以分解成为看两个结点(左结点和右结点)进行递归,来判断是否为镜像;

2、注意起始条件的设置和结束的条件,是其两个结点都是叶子结点的时候结束;

完整的代码:

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)
            return true;
        return isEqual(root.left,root.right);
    }
    public boolean isEqual(TreeNode root1,TreeNode root2){
        if(root1==null && root2==null)
            return true;
        if(root1==null || root2==null)
            return false;
        if(root1.val != root2.val)
            return false;
        return isEqual(root1.left,root2.right)&&isEqual(root1.right,root2.left);//关键代码,镜像特点
    }
}







猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/80315544