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