前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer——平衡二叉树

剑指offer——平衡二叉树

作者头像
AI那点小事
发布2020-04-18 00:47:49
2520
发布2020-04-18 00:47:49
举报
文章被收录于专栏:AI那点小事AI那点小事

概要

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


思路

如果树为空,返回true。否则递归判断每个树节点的其左右子树高度之差的绝对值是否为0或者1,若是返回true,不是返回false。 注明:这里平衡二叉树不需要是二叉排序树,国内教材为了讲述方便,默认平衡二叉树前提为二叉排序树。


C++ AC代码

#include <iostream>
#include <cmath> 
using namespace std;

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class Solution {
    public:
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot == NULL){
                return true;
            }
            return this->check_Height(pRoot);
        }

        bool check_Height(TreeNode* pRoot){
            if(pRoot == NULL){
                return true;
            }
            int left = this->TreeDepth(pRoot->left);
            int right = this->TreeDepth(pRoot->right);
            bool flag;
            if(abs(left-right) <= 1){
                return this->IsBalanced_Solution(pRoot->left) && this->IsBalanced_Solution(pRoot->right); 
            }else{
                return false;
            }
        }

        int TreeDepth(TreeNode* pRoot){
            if(pRoot == NULL){
                return 0;
            }
            int left = this->TreeDepth(pRoot->left);
            int right = this->TreeDepth(pRoot->right);
            return (left>right)?left+1:right+1;
        }
};

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概要
  • 思路
  • C++ AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档