leetCode110.BalancedBinaryTree平衡二叉树
110. 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.
题目大意:
判断一颗二叉树是否为平衡二叉树。
思路:
做一个辅助函数来求的树的高度。
通过辅助函数来递归求解。
代码如下:
/** * 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: int depth(TreeNode* root) { if(!root) return 0; int l = depth(root->left) ; int r = depth(root->right) ; return 1 + ((l > r)?l:r); } bool isBalanced(TreeNode* root) { if(!root) return true; else { int l = depth(root->left); int r = depth(root->right); if(l + 1 < r || r + 1left) && isBalanced(root->right) ); } } };
2016-08-08 00:25:26
网页名称:leetCode110.BalancedBinaryTree平衡二叉树
路径分享:http://azwzsj.com/article/gdhicj.html