2020年9月9日 星期三

LeetCode 110. Balanced Binary Tree [Easy] [C++] 解題筆記

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 left and right subtrees of every node differ in height by no 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.

想法:

        這題基本上就直接採用 DFS,buttom up 的方式從 leaf node 開始回傳當前高度,並同時判斷左右子樹高度差是否大於 1 。


完整程式碼:

class Solution {

public:

    bool balanced;

    int traverse(TreeNode* root) {

        if (root == nullptr || !balanced) { return 0; }

        int left_h = traverse(root->left);

        int right_h = traverse(root->right);

        if (abs(left_h - right_h) > 1) {

            balanced = false;

        }

        return max(left_h, right_h) + 1;

    }

    bool isBalanced(TreeNode* root) { 

        balanced = true;

        traverse(root);

        return balanced;

    }

};


沒有留言:

張貼留言