[LeetCode每日一题]101. Symmetric Tree
2020/2/21小于 1 分钟
题目如下:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
eg:
1
/ \
2 2
/ \ / \
3 4 4 3
true
1
/ \
2 2
\ \
3 3
false
给定一棵二叉树,让我们来判断它是不是对称的。解这个问题的思路是从根节点出发,分别向左儿子和右儿子两个方向出发遍历二叉树,先看左右儿子节点的值是否相等,不等则返回false。然后调用递归func(left.left, right.right)和func(left.right, right.left),两者均为真时返回true,否则返回false。 代码如下:
/**
* 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 isSymmetric(root.left, root.right);
}
public boolean isSymmetric(TreeNode left, TreeNode right) {
if (left == null || right == null) {
return left == right;
}
if (left.val != right.val) {
return false;
}
return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}
}