• 二叉平衡树


    题目描述:

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。

    基本知识:

    平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树。

    且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

     1 class Solution {
     2     int ldep = 0;
     3     int rdep = 0;
     4 public:
     5     int TreeDepth(TreeNode* pRoot){
     6         if(!pRoot) return 0 ;
     7             return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right));
     8     }
     9     bool IsBalanced_Solution(TreeNode* pRoot) {
    10         if(!pRoot)
    11             return true;
    12         ldep = TreeDepth(pRoot->left);
    13         rdep = TreeDepth(pRoot->right);
    14         if(ldep - rdep > 1 || rdep - ldep > 1)
    15             return false;
    16         else
    17         {
    18             IsBalanced_Solution(pRoot->left);
    19             IsBalanced_Solution(pRoot->right);
    20         }
    21         return true;
    22     }
    23 };

    小黑的代码:

    class Solution {
    public:
        int IsBalance(TreeNode* pRoot) {
            if(pRoot == NULL) return 0;
            int ldep = IsBalance(pRoot -> left);
            int rdep = IsBalance(pRoot -> right);
            
            if(abs(ldep - rdep) <= 1 && ldep != -1 && rdep != -1) {
                return max(1 + ldep, 1 + rdep);
            }
            else return -1;
        }
        
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(IsBalance(pRoot) == -1) return false;
            else return true;
        }
    };

     小黑的改进:

    class Solution {
    public:
        int IsBalance(TreeNode* pRoot) {
            if(pRoot == NULL) return 0;
            
            int ldep = IsBalance(pRoot -> left);
            if(ldep == -1) return -1;
            int rdep = IsBalance(pRoot -> right);
            if(rdep == -1) return -1;
            
            if(abs(ldep - rdep) <= 1 ) {
                return max(1 + ldep, 1 + rdep);
            }
            else return -1;
        }
        
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(IsBalance(pRoot) == -1) return false;
            else return true;
        }
    };
  • 相关阅读:
    1040. Moving Stones Until Consecutive II
    999. Available Captures for Rook
    1035. Uncrossed Lines
    1031. Maximum Sum of Two Non-Overlapping Subarrays
    配置启动挂载:fstab文件详解
    Linux下某个进程CPU占用率高分析方法
    linux中uptime命令查看linux系统负载
    强大的strace命令用法详解
    公司内网,配置代理以后无法使用yum源
    sshd_config配置文件
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/8778751.html
Copyright © 2020-2023  润新知