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ù)題目中的定義,高度平衡二叉樹是每一個結點的兩個子樹的深度差不能超過1,那么我們肯定需要一個求各個點深度的函數(shù),然后對每個節(jié)點的兩個子樹來比較深度差,時間復雜度為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));
}
};
上面那個方法正確但不是很高效,因為每一個點都會被上面的點計算深度時訪問一次,我們可以進行優(yōu)化。方法是如果我們發(fā)現(xiàn)子樹不平衡,則不計算具體的深度,而是直接返回-1。那么優(yōu)化后的方法為:對于每一個節(jié)點,我們通過checkDepth方法遞歸獲得左右子樹的深度,如果子樹是平衡的,則返回真實的深度,若不平衡,直接返回-1,此方法時間復雜度O(N),空間復雜度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/
到此這篇關于C++實現(xiàn)LeetCode(110.平衡二叉樹)的文章就介紹到這了,更多相關C++實現(xiàn)平衡二叉樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++實現(xiàn)LeetCode(107.二叉樹層序遍歷之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(107.二叉樹層序遍歷之二),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07
C語言實現(xiàn)一個文件版動態(tài)通訊錄流程詳解
這篇文章主要介紹了C語言實現(xiàn)一個文件版動態(tài)通訊錄流程,希望大家能從這篇文章中收獲到許多,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-01-01

