iT邦幫忙

2024 iThome 鐵人賽

0
佛心分享-刷題不只是刷題

刷經典 LeetCode 題目系列 第 43

經典LeetCode 110. Balanced Binary Tree

  • 分享至 

  • xImage
  •  

Balanced Binary Tree 這題要求判斷一個二元樹是否為「平衡的」,即每個節點的左右子樹的高度差不能超過 1。

題目:

給定一個二元樹,判斷它是否是一棵高度平衡的二元樹。

一個二元樹每個節點的左右兩個子樹的高度差不超過 1。

解題思路

使用 DFS 後序

DFS 的深度計算是由底部開始往上進行計算,先算出子節點的深度,然後將深度資訊逐層傳遞回父節點,直到根節點。

空節點深度是0,當你往上回朔時,會逐步加回每一層的深度,

實作:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        int depth = 0;
        return isBalanced(root, depth);
    }
private:
    bool isBalanced(TreeNode* root, int& depth) {
        if (root == nullptr) {
            depth = 0;
            return true;
        }

        int leftDepth = 0;
        bool isLeftBalanced = isBalanced(root->left, leftDepth);
        int rightDepth = 0;
        bool isRightBalanced = isBalanced(root->right, rightDepth);

        depth = max(leftDepth, rightDepth) + 1; // +1 加上當前層這層的深度

        return isLeftBalanced && isRightBalanced && abs(leftDepth-rightDepth) <= 1;
    }
};

參考:
#110. Balanced Binary Tree


上一篇
經典LeetCode 383. Ransom Note
系列文
刷經典 LeetCode 題目43
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言