【Balanced Binary Tree】cpp
2015-07-12 14:17
597 查看
题目:
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.
代码:
tips:
第一次刷这leetcode把此题漏掉了。
注意balanced tree是指every node:
(1)判断每个节点left和right深度是否相等
(2)再判断left和right分别是不是balanced的
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) { if (!root) return true; if ( abs(Solution::height(root->left)-Solution::height(root->right)) <= 1 ) { return Solution::isBalanced(root->left) && Solution::isBalanced(root->right); } else { return false; } } static int height(TreeNode* p) { if (!p) return 0; return max(Solution::height(p->left),Solution::height(p->right))+1; } };
tips:
第一次刷这leetcode把此题漏掉了。
注意balanced tree是指every node:
(1)判断每个节点left和right深度是否相等
(2)再判断left和right分别是不是balanced的
相关文章推荐
- C语言调试接口
- C语言之基本算法27—条件余数
- C语言之基本算法26—佩尔方程求解
- c++primer之auto类型说明符
- C语言学习笔记——结构体
- C++ primer读书笔记 3
- C语言编程易错要点
- C语言-对一个结构体中的字段进行排序
- C++ Primer 学习笔记_98_特殊的工具和技术 --优化内存分配
- stl非变易算法(二)
- C++腾讯笔试题
- c++ primer之const限定符
- C++拷贝构造函数详解
- 一个完整的C++程序SpreadSheet - 1) 类的声明和定义
- VC++ListBox(列表框)的使用
- C++11并发之std::mutex
- C++11并发之std::thread
- C++迭代器 iterator
- C++单件模式
- 一个简单链表的C++实现