Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).html
For example, this binary tree is symmetric:node
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:算法
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.post
判断二叉树是不是平衡树,好比有两个节点n1, n2,咱们须要比较n1的左子节点的值和n2的右子节点的值是否相等,同时还要比较n1的右子节点的值和n2的左子结点的值是否相等,以此类推比较完全部的左右两个节点。咱们能够用递归和迭代两种方法来实现,写法不一样,可是算法核心都同样。this
解法一:url
class Solution { public: bool isSymmetric(TreeNode *root) { if (!root) return true; return isSymmetric(root->left, root->right); } bool isSymmetric(TreeNode *left, TreeNode *right) { if (!left && !right) return true; if (left && !right || !left && right || left->val != right->val) return false; return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left); } };
迭代写法须要借助两个队列queue来实现,咱们首先判空,若是root为空,直接返回true。不然将root的左右两个子结点分别装入两个队列,而后开始循环,循环条件是两个队列都不为空。在while循环中,咱们首先分别将两个队列中的队首元素取出来,若是两个都是空结点,那么直接跳过,由于咱们尚未比较完,有可能某个结点没有左子结点,可是右子结点仍然存在,因此这里只能continue。而后再看,若是有一个为空,另外一个不为空,那么此时对称性已经被破坏了,不用再比下去了,直接返回false。若两个结点都存在,可是其结点值不一样,这也破坏了对称性,返回false。不然的话将node1的左子结点和右子结点排入队列1,注意这里要将node2的右子结点和左子结点排入队列2,注意顺序的对应问题。最后循环结束后直接返回true,这里没必要再去check两个队列是否同时为空,由于循环结束后只多是两个队列均为空的状况,其余状况好比一空一不空的直接在循环内部就返回false了,参见代码以下:spa
解法二:code
class Solution { public: bool isSymmetric(TreeNode* root) { if (!root) return true; queue<TreeNode*> q1, q2; q1.push(root->left); q2.push(root->right); while (!q1.empty() && !q2.empty()) { TreeNode *node1 = q1.front(); q1.pop(); TreeNode *node2 = q2.front(); q2.pop(); if (!node1 && !node2) continue; if((node1 && !node2) || (!node1 && node2)) return false; if (node1->val != node2->val) return false; q1.push(node1->left); q1.push(node1->right); q2.push(node2->right); q2.push(node2->left); } return true; } };
参考资料:htm
https://leetcode.com/problems/symmetric-tree/blog