1. 程式人生 > >【LeetCode筆記】Balanced Binary Tree 高度平衡二叉樹

【LeetCode筆記】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 every node never differ by more than 1.


思路:

用一個輔助函式求深度,然後每次對左右子樹的深度進行比較,差值大於1,則說明不是高度平衡二叉樹;差值小於等於1,則遞迴分別對左右子樹求深度差,對左子樹的深度差結果和右子樹的的深度差結果進行與運算。

注意!不能按照求深度部分的程式碼中的註釋部分返回,否則會顯示超時!

所以遞迴函式儘量少使用,多次需要用到遞迴值時,儘量先把遞迴返回值存入臨時變數,而不是每用到一次就計算一次!

/**
 * 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 geth(TreeNode* root){     //求深度的子函式
        if(root==NULL)
            return 0;
        else{
            int l = geth(root->left);
            int r = geth(root->right);
            return 1+(l>r?l:r);
        }
           // return geth(root->left)>geth(root->right)?geth(root->left)+1:geth(root->right)+1;  //不能每用到一次遞迴就重新計算一次,會超時!
    }
    bool isBalanced(TreeNode* root) {
        if (root==NULL)
            return true;
        else{
            //printf("root->left= %d\nroot->right= %d\nl-r= %d\n",geth(root->left),geth(root->right),abs(geth(root->left)-geth(root->right)));
            if((abs(geth(root->left)-geth(root->right))>1)){
                printf("false!\n");
                return false;
            }
            else 
                return isBalanced(root->left)&&isBalanced(root->right);
        }
    }
};