[leetcode][tree][dfs] Balanced Binary Tree
2015-05-21 13:02
260 查看
题目:
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.
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 height; return isBalancedCore(root, height); } private: bool isBalancedCore(TreeNode* root, int &height){//如果该树不平衡,返回false;如果该树平衡,返回true并通过height返回该树的高度 if(NULL == root){//递归终止条件,此时必须给height赋0值 height = 0; return true; } int leftHeight;//左子树的高度(后面函数调用过程中将赋值) int rightHeight;//右子树的高度(后面函数调用过程中将赋值) if(isBalancedCore(root->left, leftHeight) && isBalancedCore(root->right, rightHeight) && abs(leftHeight-rightHeight) <= 1){ height = 1+max(leftHeight, rightHeight); return true; } return false; } };
相关文章推荐
- leetcode 110. Balanced Binary Tree DFS
- 【Leetcode】110. Balanced Binary Tree 【DFS】
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- leetcode 110 Balanced Binary Tree(DFS)
- leetcode:110 Balanced Binary Tree-每日编程第十九题
- Leetcode Balanced Binary Tree
- LeetCode_Balanced Binary Tree
- leetcode Balanced Binary Tree
- leetcode -- 110. Balanced Binary Tree 【二叉树是否平衡】
- 【LeetCode】Balanced Binary Tree 算法优化 解题报告
- Balanced Binary Tree -- LeetCode
- LeetCode---Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- 110. Balanced Binary Tree LeetCode
- [LeetCode 110] Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- 【LeetCode】110. Balanced Binary Tree(Easy)解题报告
- [LeetCode]Balanced Binary Tree
- leetcode - Balanced Binary Tree
- LeetCode 110 Balanced Binary Tree