对称二叉树 · symmetric binary 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
复习了还是不会的地方:分为主从函数,主函数中只需要判断第一个左右子树是否相等
isSymmetricHelper(root.left, root.right);
/**
* 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) {
//corner case
if (root == null) {
return true;
}
return isSymmetricHelper(root.left, root.right);
}
public boolean isSymmetricHelper(TreeNode left, TreeNode right) {
//all null
if (left == null && right == null) {
return true;
}
//one null
if (left == null || right == null) {
return false;
}
//not same
if (left.val != right.val) {
return false;
}
//same
return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left);
//don't forget the function name
}
}