101. 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
解析:给定一颗二叉树,判断是否对称。可以使用递归求解,先判断左右子节点是否相等,不相等就返回false,如果相等就比较 左孩子的左子树 和右孩子的右子树是否相等,同时比较 左孩子的右子树和右孩子的左子树是否相等。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
bool isSame(TreeNode* left ,TreeNode* right){
if(left == NULL && right == NULL) return true ;
if((left != NULL && right == NULL) || (left == NULL && right != NULL) || (left->val != right->val))
return false ;
return isSame(left->left,right->right) && isSame(left->right,right->left);
}
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true ;
return isSame(root->left,root->right);
}
};