积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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.

===========

题目:判断一个二叉树是否是平衡二叉树?

====

什么是平衡二叉树,左右子树的高度差<=1

我们定义的balacedHeight函数的作用就是,返回平衡二叉树的树高,

如果查到此二叉树非平衡,直接return -1;

-----------

code如下:

/**
 * 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:
    bool isBalanced(TreeNode* root) {
       return balanceHeight(root) >=0; 
    }
    
    int balanceHeight(TreeNode *root){
///此如果树为平衡二叉树,返回二叉树的树高
///如果树为非平衡二叉树,返回-1;注意这个-1会一直向上传递的,一直向上传到根节点root上.
if(root==nullptr) return 0; int left = balanceHeight(root->left); int right = balanceHeight(root->right); if(left<0 || right<0) return -1;///判断左右子树是不是平衡的,否则传递-1
     if(
abs(left-right)>1) return -1;///判断树是否是平衡,否则返回-1
     return max(left,right)+1;///max(left,right)左右子树的树高的最大值,+1后是当前节点的树高
  }
};

 

posted on 2016-06-27 21:48  x7b5g  阅读(179)  评论(0编辑  收藏  举报