【LeetCode】 101. Symmetric Tree 对称二叉树(Easy)(JAVA)
题目地址: https://leetcode.com/problems/symmetric-tree/
题目描述:
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:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.
题目大意
给定一个二叉树,检查它是否是镜像对称的。
解题方法
1、采用递归方法
2、找出递归的条件,left.left == right.right,left.right == right.left
/**
* 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 iH(root.left, root.right);
}
public boolean iH(TreeNode left, TreeNode right) {
if (left == null || right == null) return left == right;
return left.val == right.val && iH(left.left, right.right) && iH(left.right, right.left);
}
}
执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 37.8 MB, 在所有 Java 提交中击败了 36.25% 的用户