[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

思路:
判断一棵树是否为镜像的,首先判断其是否为空,若为空也是镜像。若不为空,调用函数来判断左右子树是否满足镜像。判断左右子树是否满足镜像的函数有两个节点的参数,若两个节点啊都为null,返回true;若其中有一个为null,返回false;若两节点的val值相等,返回节点1左子树和节点2右子树是否为镜像和节点1右子树和节点2左子树是否为镜像的结果的&&结果,否则返回false。

代码:

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null){
            return true;
        }
        return isSymmetric(root.left,root.right);
    }
    public boolean isSymmetric(TreeNode l,TreeNode r){
        if(l==null&&r==null){
            return true;
        }
        if(l==null||r==null){
            return false;
        }
        if(l.val==r.val){
            return isSymmetric(l.left,r.right)&&isSymmetric(l.right,r.left);
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41618373/article/details/83896298