当前位置:网站首页>110. balanced binary tree recursive method

110. balanced binary tree recursive method

2022-06-24 08:52:00 Mr Gao

110. Balanced binary trees

Given a binary tree , Determine if it's a highly balanced binary tree .

In this question , A height balanced binary tree is defined as :

 Every node of a binary tree   The absolute value of the height difference between the left and right subtrees is not more than  1 .

Example 1:
 Insert picture description here

Input :root = [3,9,20,null,null,15,7]
Output :true

Example 2:
 Insert picture description here

Input :root = [1,2,2,3,3,null,null,4,4]
Output :false

Example 3:

Input :root = []
Output :true
The solution code is as follows :

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
 int f(struct TreeNode* root,int *r){
    
     if(root&&(*r)==0){
    
         int a=f(root->left,r)+1;
         int b=f(root->right,r)+1;
         if(abs(a-b)>=2){
    
            *r=1;
         }
         if(a>b){
    
             return a;
         }
         else{
    
             return b;
         }

     }
     else{
    
         return 0;
     }
 }


bool isBalanced(struct TreeNode* root){
    
    int *r=(int *)malloc(sizeof(int));
    *r=0;
   int a= f(root,r);
    if(*r==1){
    
        return false;
    }
    return true;


}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240629000020.html