【leetcode】 Balanced Binary Tree
来源:互联网 发布:淘宝退货不要菜鸟驿站 编辑:程序博客网 时间:2024/05/21 11:11
From : 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.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isBalanced(TreeNode* root, int& dep) {if(!root) {dep=0; return true;}int left, right;if(isBalanced(root->left, left) && isBalanced(root->right, right)) {if(abs(right-left) <= 1) {dep = 1+max(left, right);return true;}}return false;} bool isBalanced(TreeNode *root) { int dep; return isBalanced(root, dep); }};
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution {private static class Depth {int v = 0;}public boolean isBalanced(TreeNode root) {if (root == null) {return true;}return isBalanced(root, new Depth());}// dep is the deep of rootboolean isBalanced(TreeNode root, Depth dep) {if (root == null) {dep.v = 0;return true;}Depth left = new Depth(), right = new Depth();if (isBalanced(root.left, left) && isBalanced(root.right, right)) {if (Math.abs(right.v - left.v) <= 1) {dep.v = 1 + Math.max(right.v, left.v);return true;}}return false;}}
0 0
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode-Balanced Binary Tree
- LeetCode - Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- LeetCode | Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- kali linux 的初始化及数据库postgresql的初始化并链接
- 【C++】String类中的运算符重载
- Java 爬虫
- python的zip函数
- 网站优化:测试网站速度的8款免费工具推荐
- 【leetcode】 Balanced Binary Tree
- android shape
- 对编程语言的认识
- 如何有效防范SQL注入
- 百度地图 Android开发
- 图像处理之六边形网格分割效果
- 12款很棒的浏览器兼容性测试工具推荐
- 屏幕适配
- ecshop最新历史版本 :邮件服务器设置