110. Balanced Binary Tree
Posted 积少成多
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了110. Balanced Binary Tree相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章