LeetCode101.对称二叉树

题目来源:

https://leetcode-cn.com/problems/symmetric-tree/

题目描述:

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

        1
       / \
      2   2
       \   \
       3    3

题目来源:https://leetcode-cn.com/problems/symmetric-tree/description/

 

解题思路:1.如果该二叉树为空,直接返回ture

                  2.如果该二叉树根节点的左右子女相等,则利用递归判断左子树和右子树是否完全对称

                  3.判断左右子树是否完全对称就可看成,左子树的左子树和右子树的右子树对称,且左子树的右子树和右子树的左子                      树对称。然后开始递归判断。有一个环节为false则该二叉树不对称

 

代码实现:

    class Solution {
        public boolean isSymmetric(TreeNode root) {
            if (root == null) {
                return true;
            }
            return isSymmetric(root.left, root.right);
     
        }
     
        public boolean isSymmetric(TreeNode left, TreeNode right) {
            if (left == null && right == null) {
                return true;
            }
            if (left == null || right == null) {
                return false;
            }
            return left.val == right.val && isSymmetric(left.left, right.right) &&
                    isSymmetric(left.right, right.left);
        }
    }
---------------------
作者:晨初听雨
来源:CSDN
原文:https://blog.csdn.net/qq_39241239/article/details/82289563
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-28 10:33  天涯海角路  阅读(98)  评论(0)    收藏  举报