作者SuiseiLeda (彗星雷達)
看板Marginalman
標題Re: [LeetCode] 刷到面試 Grind169 C++
時間Sun Mar 19 15:25:31 2023
110. Balanced Binary Tree easy題
這題有偷看別人怎麼寫
我好爛
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
bool balanced = true;
height(root, &balanced);
return balanced;
}
private:
int height(TreeNode* root, bool* balanced){
if(!root) return 0;
int left_height = height(root->left, balanced);
int right_height = height(root->right, balanced);
if(abs(left_height - right_height)>1) {
*balanced = false;
return -1;
}
return max(left_height, right_height) + 1;
}
};
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.157.124 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1679210733.A.898.html
推 PyTorch: 大師 03/19 15:37
推 DreaMaker167: 大師 03/19 15:37
推 kalama450: 大師 03/19 15:38
推 DDFox: 你很棒 03/19 15:43
推 NTHUlagka: 大師 03/19 23:01