码迷,mamicode.com
首页 > 其他好文 > 详细

110. Balanced Binary Tree

时间:2016-06-27 23:01:06      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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后是当前节点的树高
  }
};

 

110. Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5621687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!