16. 이진 트리가 대칭인지 확인

제목 설명

이진 트리가 주어지면 Qi가 자신의 거울 이미지인지 (즉, 대칭인지 여부) 판단합니다.
예 : 다음 이진 트리는 대칭
     1
    / \
  2 2
 / \ / \
3 4 4 3
다음 이진 트리 비대칭입니다.
    1
    / \
  2 2
    \ \
    3 3
비고 :
재귀와 반복을 사용하여이 문제를 해결할 수 있기를 바랍니다.

예 1

시작하다

{1,2,2}

반환 값

진실

예 2

시작하다

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

반환 값

false

 

암호:

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);
    }
}

 

추천

출처blog.csdn.net/xiao__jia__jia/article/details/113447047