力扣 101. 对称二叉树 Java

101. 对称二叉树

难度简单1872

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

力扣 101. 对称二叉树 Java_第1张图片

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

力扣 101. 对称二叉树 Java_第2张图片

输入:root = [1,2,2,null,3,null,3]
输出:false

提示:

  • 树中节点数目在范围 [1, 1000] 内
  • -100 <= Node.val <= 100

进阶:你可以运用递归和迭代两种方法解决这个问题吗?

/**
 * 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 p(root.left,root.right);
    }
	
	 private boolean p(TreeNode left, TreeNode right) {
		 if(left==null&&right==null)
			 return true;
		 if(left==null||right == null)
			 return false;
		 if(left.val != right.val)
			 return false;
		 
		 return p(left.right,right.left)
				 &&p(left.left,right.right);
	 }

}

你可能感兴趣的:(力扣,java,数据结构,leetcode)