C++實現(xiàn)LeetCode(110.平衡二叉樹)
[LeetCode] 110.Balanced Binary Tree 平衡二叉樹
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é)點(diǎn)的兩個子樹的深度差不能超過1,那么我們肯定需要一個求各個點(diǎn)深度的函數(shù),然后對每個節(jié)點(diǎn)的兩個子樹來比較深度差,時間復(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)); } };
上面那個方法正確但不是很高效,因為每一個點(diǎn)都會被上面的點(diǎn)計算深度時訪問一次,我們可以進(jìn)行優(yōu)化。方法是如果我們發(fā)現(xiàn)子樹不平衡,則不計算具體的深度,而是直接返回-1。那么優(yōu)化后的方法為:對于每一個節(jié)點(diǎn),我們通過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); } };
類似題目:
參考資料:
https://leetcode.com/problems/balanced-binary-tree/
到此這篇關(guān)于C++實現(xiàn)LeetCode(110.平衡二叉樹)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)平衡二叉樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實現(xiàn)LeetCode(107.二叉樹層序遍歷之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(107.二叉樹層序遍歷之二),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C語言實現(xiàn)一個文件版動態(tài)通訊錄流程詳解
這篇文章主要介紹了C語言實現(xiàn)一個文件版動態(tài)通訊錄流程,希望大家能從這篇文章中收獲到許多,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01C語言中進(jìn)行大小寫字母轉(zhuǎn)化的示例代碼
C語言標(biāo)準(zhǔn)庫中提供了用于大小寫轉(zhuǎn)換的函數(shù),使得這一操作變得簡單而高效,本文將詳細(xì)介紹如何在C語言中進(jìn)行大小寫字母的轉(zhuǎn)換,包括相關(guān)的函數(shù)和示例代碼,需要的朋友可以參考下2024-03-03