[Leetcode]Balanced Binary Tree
来源:互联网 发布:淘宝联盟赚钱吗? 编辑:程序博客网 时间:2024/06/07 01:26
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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
关于二叉树的各种递归函数,我一般都是设置为void型。如果要求某种性质(如高度)或者判断某种条件(如是否平衡),我都会用一个变量(的引用)记录。
class Solution {public: bool isBalanced(TreeNode *root) { bool balanced = true; isTreeBalanced(root, balanced); return balanced; } private: void isTreeBalanced(TreeNode *root, bool& balancedSofar) { // 判断整棵树是否平衡 if(root == NULL || !balancedSofar) return; if(!isNodeBalanced(root)) { balancedSofar = false; return; } isTreeBalanced(root->left, balancedSofar); isTreeBalanced(root->right, balancedSofar); } bool isNodeBalanced(TreeNode *root) { // 判断节点是否平衡 if(root == NULL) return true; int leftTreeDepth = 0; height(root->left, 1, leftTreeDepth); int rightTreeDepth = 0; height(root->right, 1, rightTreeDepth); if(leftTreeDepth-rightTreeDepth > 1 || rightTreeDepth - leftTreeDepth > 1) return false; else return true; }void height(TreeNode *root, int currentDepth, int& maxD) { // 求树的高度(根为1)if (root == NULL)return;if (root->left == NULL && root->right == NULL && currentDepth > maxD) { // 叶节点maxD = currentDepth;return;}height(root->left, currentDepth + 1, maxD);height(root->right, currentDepth + 1, maxD);}};
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
- setAnimation设置了不播放动画?setAnimation与startAnimation的区
- 【Spring】官网教程阅读笔记(二):消费一个RESTweb服务
- Combinations --LeetCode
- xamarin.forms 相对布局
- Catalan数
- [Leetcode]Balanced Binary Tree
- 主流php框架对比
- Android源码目录结构详解
- ASCII、Unicode、GBK和UTF-8字符编码的区别联系
- SSL和SSH有什么区别
- 自定义uiview
- 二叉树
- 【单调队列优化dp】Uvalive4327丨Poj3926 Parade
- 习题2—10