Try   HackMD

【LeetCode】 110. Balanced Binary Tree

Description

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 every node never differ by more than 1.

給一棵二元樹,判斷它是不是平衡樹。

本題目對於一棵平衡樹的定義為:

對於每個節點,它左右子樹的高度相差必須小於等於一。

Example:

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.

Solution

  • 用遞迴求樹高,然後將左右子樹樹高差距做判斷,如果符合就以它們為樹根繼續做遞迴。

Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int FindHeight(TreeNode* node) { if(!node) return 0; else return max(FindHeight(node->left),FindHeight(node->right)) + 1; } bool isBalanced(TreeNode* root) { if(!root) return true; if(abs(FindHeight(root->left) - FindHeight(root->right)) > 1) return false; return isBalanced(root->left)&&isBalanced(root->right); } };
tags: LeetCode C++