您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“C++怎么實(shí)現(xiàn)平衡二叉樹(shù)”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
求二叉樹(shù)是否平衡,根據(jù)題目中的定義,高度平衡二叉樹(shù)是每一個(gè)結(jié)點(diǎn)的兩個(gè)子樹(shù)的深度差不能超過(guò)1,那么我們肯定需要一個(gè)求各個(gè)點(diǎn)深度的函數(shù),然后對(duì)每個(gè)節(jié)點(diǎn)的兩個(gè)子樹(shù)來(lái)比較深度差,時(shí)間復(fù)雜度為O(NlgN),代碼如下:
解法一:
class Solution { public: bool isBalanced(TreeNode *root) { if (!root) return true; if (abs(getDepth(root->left) - getDepth(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } int getDepth(TreeNode *root) { if (!root) return 0; return 1 + max(getDepth(root->left), getDepth(root->right)); } };
上面那個(gè)方法正確但不是很高效,因?yàn)槊恳粋€(gè)點(diǎn)都會(huì)被上面的點(diǎn)計(jì)算深度時(shí)訪問(wèn)一次,我們可以進(jìn)行優(yōu)化。方法是如果我們發(fā)現(xiàn)子樹(shù)不平衡,則不計(jì)算具體的深度,而是直接返回-1。那么優(yōu)化后的方法為:對(duì)于每一個(gè)節(jié)點(diǎn),我們通過(guò)checkDepth方法遞歸獲得左右子樹(shù)的深度,如果子樹(shù)是平衡的,則返回真實(shí)的深度,若不平衡,直接返回-1,此方法時(shí)間復(fù)雜度O(N),空間復(fù)雜度O(H),參見(jiàn)代碼如下:
解法二:
class Solution { public: bool isBalanced(TreeNode *root) { if (checkDepth(root) == -1) return false; else return true; } int checkDepth(TreeNode *root) { if (!root) return 0; int left = checkDepth(root->left); if (left == -1) return -1; int right = checkDepth(root->right); if (right == -1) return -1; int diff = abs(left - right); if (diff > 1) return -1; else return 1 + max(left, right); } };
“C++怎么實(shí)現(xiàn)平衡二叉樹(shù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。