Leetcode-101 对称二叉树

Leetcode-101 对称二叉树_第1张图片
递归:主要思想:对称二叉树是左子树的左孩子=右子树的右孩子,左子树的右孩子=右子树的左孩子,递归实现思路较为清晰

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null){
            return true;
        }
        return check(root.left,root.right);
    }

    boolean check(TreeNode l,TreeNode r){
        if(l==null&&r==null){
            return true;
        }
        if(l==null||r==null){
            return false;
        }
        if(l.val!=r.val){
            return false;
        }
        return check(l.left,r.right)&&check(l.right,r.left);
    }
}

你可能感兴趣的:(Leetcode刷题,leetcode,算法,职场和发展)