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

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

2014.1.8 04:09

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.

Solution:

  Just do as the problem says, calculate the heights and check if they meet the requirement.

  Time complexity is O(n), where n is the number of nodes in the tree. Space complexity is O(1).

Accepted code:

1 // 1AC, good~ 2 /** 3  * Definition for binary tree 4  * struct TreeNode { 5  *     int val; 6  *     TreeNode *left; 7  *     TreeNode *right; 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9  * };10  */11 class Solution {12 public:13     bool isBalanced(TreeNode *root) {14         // IMPORTANT: Please reset any member data you declared, as15         // the same Solution instance will be reused for each test case.16         if(root == nullptr){17             return true;18         }19         20         return myabs(treeHeight(root->left) - treeHeight(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);21     }22 private:23     const int &myabs(const int &num) {24         return (num >= 0 ? num : -num);25     }26     27     const int &mymax(const int &x, const int &y) {28         return (x > y ? x : y);29     }30     31     int treeHeight(TreeNode *root) {32         if(root == nullptr){33             return 0;34         }else{35             return mymax(treeHeight(root->left), treeHeight(root->right)) + 1;36         }37     }38 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3510002.html

你可能感兴趣的文章
JavaEE:Eclipse开发工具的相关使用和XML技术
查看>>
LR_问题_如何将场景中的用户设置为百分比形式
查看>>
OpenShift-OKD3.10基础环境部署
查看>>
工程师淘金:开发Android主攻四大方向
查看>>
ASP.NET MVC——Controller的激活
查看>>
javascript中Array对象
查看>>
SQLSERVER中查看谁占用了Buffer Pool
查看>>
lamp环境安装shell脚本
查看>>
ASP.NET MVC使用jQuery实现Autocomplete
查看>>
model中字段格式验证
查看>>
host路径
查看>>
查看linux 内存
查看>>
HTTP 状态码
查看>>
Ubuntu 14.10 下卸载MySQL
查看>>
练习题 求字符串是否为回文
查看>>
为了兼容性问题,本人一律淘汰不兼容如下三种浏览器的js
查看>>
RowFilter 对于已获取到的dataset进行过滤
查看>>
451. Sort Characters By Frequency
查看>>
第十五周总结
查看>>
java学习笔记-hibernate基础(1)
查看>>