判断二叉树是否是平衡二叉树(C++)

  1. 第一种方法:采用自底向上的递归方法
int height( TreeNode* root){
    
    
        if(root == NULL){
    
    
            return 0;
        }else{
    
    
            int leftheight = height(root->left);
            int rightheight = height(root->right);
            if(leftheight == -1 || rightheight == -1 || abs(leftheight-rightheight)>1){
    
    
                return -1;
            }else{
    
    
                return max(rightheight,leftheight)+1;
            }
        }
    }
    
    bool isBalanced(TreeNode* root) {
    
    
        return height(root) >= 0;
    }
  1. 第二种方法:
//自顶向下递归
    int height(TreeNode* root){
    
    
        if(root == NULL){
    
    
            return 0;
        }else{
    
    
            int left = height(root->left);
            int right = height(root->right);
            return max(left,right) + 1;
        }
    }
     bool isBalanced(TreeNode* root) {
    
    
        if(root == NULL){
    
    
            return true;
        }else{
    
    
            if(abs(height(root->left)-height(root->right))<=1 && isBalanced(root->left)
            && isBalanced(root->right)){
    
    
                return true;
            }else{
    
    
                return false;
            }
        }
    }
  1. 求树高:
 int height(TreeNode *T){
    
    
        if(T == NULL){
    
    
            return 0;
        }else{
    
    
            int leftheight = height(T->left);
            int rightheight = height(T->right);
            return max(leftheight,rightheight)+1;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_43964318/article/details/120351202