C++實現(xiàn)LeetCode(101.判斷對稱樹)
[LeetCode] 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 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.
判斷二叉樹是否是平衡樹,比如有兩個節(jié)點n1, n2,我們需要比較n1的左子節(jié)點的值和n2的右子節(jié)點的值是否相等,同時還要比較n1的右子節(jié)點的值和n2的左子結(jié)點的值是否相等,以此類推比較完所有的左右兩個節(jié)點。我們可以用遞歸和迭代兩種方法來實現(xiàn),寫法不同,但是算法核心都一樣。
解法一:
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來實現(xiàn),我們首先判空,如果root為空,直接返回true。否則將root的左右兩個子結(jié)點分別裝入兩個隊列,然后開始循環(huán),循環(huán)條件是兩個隊列都不為空。在while循環(huán)中,我們首先分別將兩個隊列中的隊首元素取出來,如果兩個都是空結(jié)點,那么直接跳過,因為我們還沒有比較完,有可能某個結(jié)點沒有左子結(jié)點,但是右子結(jié)點仍然存在,所以這里只能continue。然后再看,如果有一個為空,另一個不為空,那么此時對稱性已經(jīng)被破壞了,不用再比下去了,直接返回false。若兩個結(jié)點都存在,但是其結(jié)點值不同,這也破壞了對稱性,返回false。否則的話將node1的左子結(jié)點和右子結(jié)點排入隊列1,注意這里要將node2的右子結(jié)點和左子結(jié)點排入隊列2,注意順序的對應(yīng)問題。最后循環(huán)結(jié)束后直接返回true,這里不必再去check兩個隊列是否同時為空,因為循環(huán)結(jié)束后只可能是兩個隊列均為空的情況,其他情況比如一空一不空的直接在循環(huán)內(nèi)部就返回false了,參見代碼如下:
解法二:
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; } };
參考資料:
https://leetcode.com/problems/symmetric-tree/
到此這篇關(guān)于C++實現(xiàn)LeetCode(101.判斷對稱樹)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)判斷對稱樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言實現(xiàn)系統(tǒng)關(guān)機注銷功能
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)系統(tǒng)關(guān)機注銷功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-02-02C++實現(xiàn)查找二叉樹中和為某一值的所有路徑的示例
這篇文章主要介紹了C++實現(xiàn)查找二叉樹中和為某一值的所有路徑的示例,文中的方法是根據(jù)數(shù)組生成二叉排序樹并進(jìn)行遍歷,需要的朋友可以參考下2016-02-02