C++如何實現(xiàn)平衡二叉樹

本篇內(nèi)容介紹了“C++如何實現(xiàn)平衡二叉樹”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

10年專業(yè)網(wǎng)站制作公司歷程,堅持以創(chuàng)新為先導(dǎo)的網(wǎng)站服務(wù),服務(wù)超過成百上千家企業(yè)及個人,涉及網(wǎng)站設(shè)計、App定制開發(fā)、微信開發(fā)、平面設(shè)計、互聯(lián)網(wǎng)整合營銷等多個領(lǐng)域。在不同行業(yè)和領(lǐng)域給人們的工作和生活帶來美好變化。

平衡二叉樹

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.

求二叉樹是否平衡,根據(jù)題目中的定義,高度平衡二叉樹是每一個結(jié)點的兩個子樹的深度差不能超過1,那么我們肯定需要一個求各個點深度的函數(shù),然后對每個節(jié)點的兩個子樹來比較深度差,時間復(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));
    }
};

上面那個方法正確但不是很高效,因為每一個點都會被上面的點計算深度時訪問一次,我們可以進(jìn)行優(yōu)化。方法是如果我們發(fā)現(xiàn)子樹不平衡,則不計算具體的深度,而是直接返回-1。那么優(yōu)化后的方法為:對于每一個節(jié)點,我們通過checkDepth方法遞歸獲得左右子樹的深度,如果子樹是平衡的,則返回真實的深度,若不平衡,直接返回-1,此方法時間復(fù)雜度O(N),空間復(fù)雜度O(H),參見代碼如下:

解法二:

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++如何實現(xiàn)平衡二叉樹”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

當(dāng)前文章:C++如何實現(xiàn)平衡二叉樹
網(wǎng)址分享:http://bm7419.com/article44/pssjee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號關(guān)鍵詞優(yōu)化、軟件開發(fā)網(wǎng)站設(shè)計公司、營銷型網(wǎng)站建設(shè)、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)