101. Symmetric Tree

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

Follow up: Could you solve it both recursively and iteratively?

class Solution {
	public boolean isSymmetric(TreeNode root) {
		if(root==null) {
			return true;
		}
		//调用递归函数,比较左节点,右节点
		return dfs(root.left,root.right);
	}
	
	boolean dfs(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 dfs(left.left,right.right) && dfs(left.right,right.left);
	}
}

相关推荐

  1. 面试经典150题(101-104)

    2024-03-22 07:28:01       21 阅读
  2. IOS面试题object-c 101-110

    2024-03-22 07:28:01       16 阅读
  3. 安卓kotlin面试题 101-105

    2024-03-22 07:28:01       15 阅读
  4. LeetCode hot100-11

    2024-03-22 07:28:01       19 阅读
  5. 华为机试真题练习汇总(101~110

    2024-03-22 07:28:01       16 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-22 07:28:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-22 07:28:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-22 07:28:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-22 07:28:01       18 阅读

热门阅读

  1. 2024.3.21 ARM

    2024-03-22 07:28:01       19 阅读
  2. C++ 函数指针与回调函数

    2024-03-22 07:28:01       23 阅读
  3. 全球化战略中的技术纵深

    2024-03-22 07:28:01       18 阅读
  4. android11 系统的启动流程 的面试题目

    2024-03-22 07:28:01       21 阅读
  5. Python 机器学习 前向后向算法评估观察序列概率

    2024-03-22 07:28:01       20 阅读
  6. ChatGPT为您的论文写作提供无限可能

    2024-03-22 07:28:01       19 阅读
  7. Play on Words(UVA 10129)

    2024-03-22 07:28:01       15 阅读