LeetCode每日一题:对称二叉树

问题描述

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.

问题分析

求一棵树是不是对称的,对于一个节点,要满足他两个孩子是相同的,并且左孩子的左孩子与右孩子的右孩子要相等,左孩子的右孩子要和右孩子的左孩子相等,用递归做就行了。

代码实现

public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return isSymmetricHelper(root.left, root.right);
    }

    private boolean isSymmetricHelper(TreeNode leftChild, TreeNode rightChild) {
        if (leftChild == null && rightChild == null) return true;
        if (leftChild == null && rightChild != null) return false;
        if (leftChild != null && rightChild == null) return false;
        if (leftChild.val != rightChild.val) return false;
        return isSymmetricHelper(leftChild.left, rightChild.right) && isSymmetricHelper(leftChild.right, rightChild.left);
    }

你可能感兴趣的:(LeetCode每日一题:对称二叉树)