前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++版 - 剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解

C++版 - 剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解

作者头像
Enjoy233
发布2019-03-05 14:36:09
5300
发布2019-03-05 14:36:09
举报

剑指offer 面试题39:判断平衡二叉树

提交网址:  http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192

时间限制:1秒       空间限制:32768K      参与人数:2481

题目描述

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

分析:

平衡二叉树定义

递归解法 AC代码:

代码语言:javascript
复制
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode{
    int val; 
    TreeNode *left; 
    TreeNode *right; 
    TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
}; 
class Solution {
public:
	int getHeight(TreeNode *root)
	{
		if(root==NULL) return 0;
		int lh=getHeight(root->left);
		int rh=getHeight(root->right);
		int height=(lh<rh)?(rh+1):(lh+1);  // 记住:要加上根节点那一层,高度+1 
		return height;
	}
    bool IsBalanced_Solution(TreeNode* pRoot) {
		if(pRoot==NULL) return true;
		int lh=getHeight(pRoot->left);
		int rh=getHeight(pRoot->right);
		if(lh-rh>1 || lh-rh<-1)	return false;
		else return (IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right)); // 继续递归判断	
    }
};
// 以下为测试 
int main()
{
	Solution sol;      
    TreeNode *root = new TreeNode(1);  
    root->right = new TreeNode(2);  
    root->right->left = new TreeNode(3);      
    bool res=sol.IsBalanced_Solution(root); 
    cout<<res<<" ";
    return 0; 
}

LeetCode 110. Balanced Binary Tree

Total Accepted: 111269 Total Submissions: 326144 Difficulty: Easy

提交网址: https://leetcode.com/problems/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.

AC代码:

代码语言:javascript
复制
class Solution {
public:
	int getHeight(TreeNode *root)
	{
		if(root==NULL) return 0;
		int lh=getHeight(root->left);
		int rh=getHeight(root->right);
		int height=(lh<rh)?(rh+1):(lh+1);  // 记住:要加上根节点那一层,高度+1 
		return height;
	}
    bool isBalanced(TreeNode *root) {
		if(root==NULL) return true;
		int lh=getHeight(root->left);
		int rh=getHeight(root->right);
		if(lh-rh>1 || lh-rh<-1)	return false;
		else return (isBalanced(root->left) && isBalanced(root->right)); // 继续递归判断	
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年05月15日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 时间限制:1秒       空间限制:32768K      参与人数:2481
  • 题目描述
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档