【LeetCode】 101. Symmetric Tree (Easy) (JAVA)
Title address: https://leetcode.com/problems/symmetric-tree/
Title description:
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.
Topic
Given a binary tree, check whether it is mirror-symmetrical.
Problem solving method
1. Use the recursive method
2. Find the recursive conditions, 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);
}
}
Execution time: 0 ms, defeated 100.00% of users
in all Java submissions Memory consumption: 37.8 MB, defeated 36.25% of users in all Java submissions