LeetCode:Balanced Binary Tree
2013-11-24 15:21
316 查看
题目链接
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.
分析:判断一颗二叉树是否是平衡的,dfs递归求解,递归的过程中顺便求得树的高度 本文地址
【版权声明】转载请注明出处:/article/4879654.html
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.
分析:判断一颗二叉树是否是平衡的,dfs递归求解,递归的过程中顺便求得树的高度 本文地址
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(root == NULL)return true; if(height(root) == -1)return false; else return true; } //若root是平衡树,那么返回树的高度,否则返回-1 int height(TreeNode *root) { if(root->left == NULL && root->right == NULL)return 1; int leftHeight = 0, rightHeight = 0; if(root->left) leftHeight = height(root->left); if(leftHeight == -1)return -1; if(root->right) rightHeight = height(root->right); if(rightHeight == -1)return -1; if(abs(leftHeight-rightHeight) > 1)return -1; return 1+max(leftHeight, rightHeight); } };
【版权声明】转载请注明出处:/article/4879654.html
相关文章推荐
- LeetCode 110 Balanced Binary Tree
- [LeetCode]: 110: Balanced Binary Tree
- LeetCode题解-110-Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Leetcode 110 Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- LeetCode_110 Balanced Binary Tree
- 【leetcode】Balanced Binary Tree(middle)
- leetcode - Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- leetCode(20):Balanced binary tree 分类: leetCode 2015-06-22 08:52 190人阅读 评论(0) 收藏
- Balanced Binary Tree -- LeetCode
- leetcode之Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- [leetcode 110]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree 平衡二叉树
- leetcode 刷题之路 86 Balanced Binary Tree
- 【leetcode】110.Balanced Binary Tree
- Leetcode Balanced Binary Tree