Balanced Binary Tree

来源:互联网 发布:逸晗网络视频编辑 编辑:程序博客网 时间:2024/05/19 02:43
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.


bool isBalanced(TreeNode *root) {  if (depth(root) == -1)    return false;  return true;}int depth(TreeNode *node){  if (!node) return 0;  int leftDepth = helper(node->left);  int rightDepth = helper(node->right);  if (leftDepth == -1 || rightDepth == -1)    return -1;  if (abs(leftDepth - rightDepth) > 1)    return -1;  return leftDepth < rightDepth ? rightDepth + 1 : leftDepth + 1;}


0 0
原创粉丝点击