Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
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.
解法一:
遞歸方法,判斷一個二叉樹是否為對稱二叉樹,對非空二叉樹,則如果:
左子樹的根val和右子樹的根val相同,則表示當前層是對稱的。需判斷下層是否對稱,
此時需判斷:左子樹的左子樹的根val和右子樹的右子樹根val,左子樹的右子樹根val和右子樹的左子樹根val,這兩種情況的val值是否相等,如果相等,則滿足相應層相等,迭代操作直至最后一層。
bool isSame(TreeNode *root1,TreeNode *root2){ if(!root1&&!root2)//二根都為null, return true; //二根不全為null,且在全部為null時,兩者的val不同。 if(!root1&&root2||root1&&!root2||root1->val!=root2->val) return false; //判斷下一層。 return isSame(root1->left,root2->right)&&isSame(root1->right,root2->left); } bool isSymmetric(TreeNode* root) { if(!root) return true; return isSame(root->left,root->right); }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。