16. Determine whether the binary tree is symmetric

Title description

Given a binary tree, judge whether Qi is a mirror image of itself (that is, whether it is symmetrical).
For example: the following binary tree is symmetric
     1
    / \
  2 2
 / \ / \
3 4 4 3
The following binary tree is asymmetric.
    1
    / \
  2 2
    \ \
    3 3
Remarks:
I hope you can use recursion and iteration to solve this problem

Example 1

enter

copy

{1,2,2}

return value

copy

true

Example 2

enter

{1,2,3,3,#,2,#}

return value

false

 

Code:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    public boolean isSymmetric (TreeNode root) {
        return root == null || isCommon(root.left, root.right);
    }
    

    public static boolean isCommon(TreeNode leftNode, TreeNode rightNode) {
        if (leftNode == null && rightNode == null) {
            return true;
        }	
        if (leftNode == null || rightNode == null) {
            return false;
        }
        return leftNode.val == rightNode.val && isCommon(leftNode.left,rightNode.right) && isCommon(leftNode.right,rightNode.left);
    }
}

 

Guess you like

Origin blog.csdn.net/xiao__jia__jia/article/details/113447047