Symmetric binary trees

Given a binary tree, check if it is mirror symmetric.

See the LeetCode website for an example.

Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: Recursion

If root is empty, or if root has no children, then return true. The recursive method is then called
isSymmetric(TreeNode left, TreeNode right)To judge whether the left and right subtrees are equal, the judgment logic is to judge whether the values of the left and right subtrees are equal. If so, it will continue to judge whether the left subtree of the left subtree and the right subtree of the right subtree are equal and whether the right subtree of the left subtree and the left subtree of the right subtree are equal. Until the recursion is complete, the judgment is completed and the result is returned.

public class LeetCode_101 { public static boolean isSymmetric(TreeNode root) { if (root == null || (root.left == null &&  root.right == null)) { return true; } return isSymmetric(root.left, root.right); } public static boolean isSymmetric(TreeNode left, TreeNode right) { if (left == null && right == null) { return true; } if ((left == null && right ! = null) || (left ! = null && right == null)) { return false; } return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(2); root.left.left = new TreeNode(3); root.right.right = new TreeNode(3); System.out.println(isSymmetric(root)); }}

【 Daily Message 】
The supreme happiness of life is the conviction that we are loved.