能走出雨季的,从来不是伞,而是不惧蹚湿的自己
—— 24.12.11
101. 对称二叉树
给你一个二叉树的根节点
root
, 检查它是否轴对称。示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false提示:
- 树中节点数目在范围
[1, 1000]
内-100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
方法一 递归
思路
从根节点开始遍历,将节点的左右孩子都传入递归函数,然后不断递归,直到符合递归的终止条件后,判断二叉树是否对称,返回布尔类型的结果
递归的终止条件:
两个节点都为空,则代表是对称二叉树
两个节点中有一个为空,则代表不是对称二叉树
两个节点的值不相等,则代表不是对称二叉树
Java实现
/*** 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 dfs(root.left,root.right);}public 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);}
}
Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:if root is None:return Truereturn self.dfs(root.left, root.right)def dfs(self, left, right):if not left and not right:return Trueif not left or not right:return Falseif left.val != right.val:return Falsereturn self.dfs(left.left, right.right) and self.dfs(left.right, right.left)