博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Balanced Binary Tree
阅读量:7077 次
发布时间:2019-06-28

本文共 1382 字,大约阅读时间需要 4 分钟。

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.

分析:判断一颗二叉树是否是平衡的,dfs递归求解,递归的过程中顺便求得树的高度                                      

1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  * int val; 5  * TreeNode *left; 6  * TreeNode *right; 7  * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     bool isBalanced(TreeNode *root) {13         // IMPORTANT: Please reset any member data you declared, as14         // the same Solution instance will be reused for each test case.15         if(root == NULL)return true;16         if(height(root) == -1)return false;17         else return true;18     }19     //若root是平衡树,那么返回树的高度,否则返回-120     int height(TreeNode *root)21     {22         if(root->left == NULL && root->right == NULL)return 1;23         int leftHeight = 0, rightHeight = 0;24         if(root->left)25             leftHeight = height(root->left);26         if(leftHeight == -1)return -1;27         if(root->right)28             rightHeight = height(root->right);29         if(rightHeight == -1)return -1;30         if(abs(leftHeight-rightHeight) > 1)return -1;31         return 1+max(leftHeight, rightHeight);32     }33 };

【版权声明】转载请注明出处:

转载于:https://www.cnblogs.com/TenosDoIt/p/3440069.html

你可能感兴趣的文章
图文详解YUV420数据格式
查看>>
nginx 【logformat】日志格式
查看>>
【Linux系列】【基础版】第四章 Shell基础之正则表达式
查看>>
JWT 在 Spring 上的实践
查看>>
释放linux缓存
查看>>
4、C语言 —— 基本运算
查看>>
js判断是否是ipad还是iphone及各手机用户
查看>>
同时添加多个github ssh key的方法
查看>>
Essential Grid for ASP.NET MVC
查看>>
PDA使用异常指导手册
查看>>
goroutine背后的系统知识
查看>>
ubuntu安装nrpe无法安装问题
查看>>
命令操作
查看>>
SAN 光纤交换机配置远距离级联(EF)操作
查看>>
Web性能优化方案
查看>>
关于proteus闪退问题
查看>>
Android :实现一个手机卫士的一些要点
查看>>
mysql的备份与恢复
查看>>
Python SocketServer 网络服务器的框架一:基本知识
查看>>
Mac下Android Studio中获取SHA1和MD5
查看>>