LeetCode: Balanced Binary Tree
2014-08-27 21:02
106 查看
[b]LeetCode: Balanced Binary Tree[/b]
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.
地址:https://oj.leetcode.com/problems/balanced-binary-tree/
算法:递归解决,并且在递归的过程中求出树的深度。代码:
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.
地址:https://oj.leetcode.com/problems/balanced-binary-tree/
算法:递归解决,并且在递归的过程中求出树的深度。代码:
/** * 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) { if(!root){ return true; } int depth = 0; return subIsBalanced(root,depth); } bool subIsBalanced(TreeNode *root, int &depth){ if(!root){ depth = 0; return true; } int left_depth; bool left = subIsBalanced(root->left,left_depth); int right_depth; bool right = subIsBalanced(root->right,right_depth); depth = left_depth > right_depth ? left_depth + 1 : right_depth + 1; if(left && right){ if(left_depth > right_depth + 1 || right_depth > left_depth + 1){ return false; } return true; } return false; } };
相关文章推荐
- [Leetcode] Balanced Binary Tree
- leetcode -- Balanced Binary Tree TODO
- [LeetCode] Balanced Binary Tree
- Balanced Binary Tree——LeetCode
- leetcode_110 Balanced Binary Tree
- leetcode Balanced Binary Tree
- Balanced Binary Tree-LeetCode
- leetcode Balanced Binary Tree
- Leetcode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree (Java)
- LeetCode学习篇二十五——Balanced Binary Tree
- [leetcode]110. Balanced Binary Tree
- [Leetcode]110. Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [C]LeetCode:Balanced Binary Tree
- [leetcode]Balanced Binary Tree @ Python
- LeetCode 110 Balanced Binary Tree(平衡二叉树)(*)
- 开始刷题leetcode day3:Balanced Binary Tree
- leetcode: Balanced Binary Tree
- 【LeetCode笔记】Balanced Binary Tree 高度平衡二叉树