LeetCode Balanced Binary Tree
2015-01-19 10:51
183 查看
题目
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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool innerIsBalanced(TreeNode *root,int &height) //判断平衡,并求高度 { if(root==NULL) //空 { height=0; return true; } int height_left,height_right; //左子树高度,右子树高度 if(!innerIsBalanced(root->left,height_left)) //判断左子树平衡,求高度 return false; if(!innerIsBalanced(root->right,height_right)) //判断右子树平衡,求高度 return false; height=max(height_left,height_right)+1; //计算当前子树的高度 return abs(height_left-height_right)<=1; //判断平衡性 } bool isBalanced(TreeNode *root) { int height; return innerIsBalanced(root,height); } };
相关文章推荐
- LeetCode | Balanced Binary Tree(平衡二叉树)
- [leetcode] 110. Balanced Binary Tree
- LeetCode 110: Balanced Binary Tree
- LeetCode:Balanced Binary Tree
- LeetCode--balanced-binary-tree
- LeetCode110.Balanced Binary Tree题解
- [LeetCode] Balanced Binary Tree
- 和大神们学习每天一题(leetcode)-Balanced Binary Tree
- Leetcode Balanced Binary Tree
- 【LeetCode】110. Balanced Binary Tree
- 【LEETCODE】110-Balanced Binary Tree
- 【LeetCode 110】Balanced Binary Tree (C++)
- 【leetcode】Balanced Binary Tree
- LeetCode110—Balanced Binary Tree
- LeetCode之Balanced Binary Tree
- LeetCode题目笔记(四) -- Check if a binary tree is balanced
- [LeetCode] Balanced Binary Tree
- LeetCode | Balanced Binary Tree
- leetcode 110 Balanced Binary Tree(DFS)
- leetcode之Balanced Binary Tree