欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 101.对称二叉树

程序员文章站 2022-03-26 21:37:12
...

101.对称二叉树

题目:

LeetCode 101.对称二叉树

思路:
  • 递归思路:
    • 镜像对称,就是从根节点依次往下
    • 比较左子树的左子树值是不是和右子树的右子树的值相等,并且左子树的右子树值是不是和右子树的左子树的值相等
    • 全部相等即可
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        return judgeLeftRight(root, root);
    }

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

LeetCode 101.对称二叉树