Balanced Binary Tree

来源:互联网 发布:限制安装软件 编辑:程序博客网 时间:2024/05/17 21:54

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.

Subscribe to see which companies asked this question

判断一个节点的左右深度差值小于1

先求左右节点的什么,然后进行判断。深度就是求该节点到自身左右树的最深距离+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:   nt height(TreeNode* root) {          if(root==NULL)              return 0;          else{              int l=height(root->left);              int r=height(root->right);              return 1+((l>r)?l:r);          }      }      bool isBalanced(TreeNode *root) {          if(root==NULL)              return true;          else{              int l,r;              l=height(root->left);              r=height(root->right);              if((l>r+1)||(r>l+1))                  return false;              else                  return isBalanced(root->left)&&isBalanced(root->right);          }      }  };


0 0