16.二分木が対称であるかどうかを判断します

タイトル説明

二分木が与えられた場合、Qiがそれ自体の鏡像であるかどうか(つまり、対称であるかどうか)を判断します。
例:次の二分木は対称です
     1
    / \
  2 2
 / \ / \
3 4
43次の二分木非対称です。
    1
    / \
  2 2
    \ \
    3 3
備考:
この問題を解決するために再帰と反復を使用できることを願っています

例1

入る

コピー

{1,2,2}

戻り値

コピー

true

例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