[关闭]
@snuffles 2019-04-02T13:43:27.000000Z 字数 682 阅读 865

L110平衡二叉树


给定一个二叉树,判断它是否是高度平衡的二叉树。

解1:递归算树的深度return 1+max(left,right)

  1. bool isBalanced(TreeNode* root) {
  2. if(checkDepth(root) == -1) return false;
  3. else return true;
  4. }
  5. int checkDepth(TreeNode * root){
  6. if(root == NULL) return 0;
  7. int left = checkDepth(root->left);
  8. if (left == -1) return -1;
  9. int right = checkDepth(root->right);
  10. if (right == -1) return -1;
  11. if(abs(right-left)>1) return -1;
  12. else return 1+max(left,right);
  13. }
  14. // 解法2:
  15. bool isBalanced(TreeNode* root) {
  16. if(root == NULL) return true;
  17. if (abs(getDepth(root->left)-getDepth(root->right)) >1) return false;
  18. else{
  19. if(isBalanced(root->left) && isBalanced(root->right)) return true;
  20. else return false;
  21. }
  22. }
  23. int getDepth(TreeNode * root){
  24. if(root == NULL) return 0;
  25. return 1+max(getDepth(root->left),getDepth(root->right));
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注