Leetcode 树 Balanced Binary Tree
来源:互联网 发布:ubuntu搭建hadoop集群 编辑:程序博客网 时间:2024/06/07 10:21
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Balanced Binary Tree
Total Accepted: 13700 Total Submissions: 42780Given 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.
题意:给定一棵二叉树,判断它是不是高平衡的。高平衡指的是每一个节点的左右子树的深度差不超过1
思路:bfs递归
1.如果根节点的左右子树深度之差大于1,返回false
2.如果左子树或右子树不是平衡的,返回false
3.返回true
复杂度:时间O(n), 空间O(log n)
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isBalanced(TreeNode *root){ if(!root) return true; if (abs(depth(root->left) - depth(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } int depth(TreeNode *root){ if(!root) return 0; int left_depth = depth(root->left); int right_depth = depth(root->right) ; return left_depth > right_depth ? left_depth + 1 : right_depth + 1; }};
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
- Socket编程指南及示例程序
- ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别
- sql多行拼接成字符串
- 解决运行Tomcat,报accept2的错误
- hdu4386(求四边形最大面积)
- Leetcode 树 Balanced Binary Tree
- C#学习笔记-泛型
- Page.ClientScript.RegisterStartupScript
- 以为这是成长带给我们的
- 基于栈与基于寄存器的指令集架构
- python中的对象赋值(等号赋值、深复制、浅复制)
- HTML Color Code
- Cocos2d-x学习之windows 7 android环境搭建
- Python基础01(前期工作和安装python)