溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

101. Symmetric Tree

發(fā)布時間:2020-06-25 19:15:30 來源:網(wǎng)絡(luò) 閱讀:397 作者:qdqade 欄目:編程語言

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相同,則表示當(dāng)前層是對稱的。需判斷下層是否對稱,

此時需判斷:左子樹的左子樹的根val和右子樹的右子樹根val,左子樹的右子樹根val和右子樹的左子樹根val,這兩種情況的val值是否相等,如果相等,則滿足相應(yīng)層相等,迭代操作直至最后一層。

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);
    }


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI