首页 > 代码库 > Balanced Binary Tree
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. 空树是一颗平衡二叉树
2. 它的左子树和右子树的高度差不超过1
3. 它的左子树和右子树也是平衡二叉树
故判断这棵树是否是平衡二叉树,不仅要求树的高度,也要判断左右子树是否均为平衡二叉树,使用树的后序遍历,求树高度的时候同时判断这棵树是否是平衡二叉书,代码如下:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 bool isBalanced(TreeNode *root) {13 return getdepth(root) > -1;14 }15 16 int getdepth(TreeNode* root) { //返回正常高度,说明是平衡二叉树,否则返回-117 if( !root ) return 0; //空树是平衡二叉树,返回018 int leftdepth = getdepth(root->left); //左子树高度19 int rightdepth = getdepth(root->right); //右子树高度20 //左子树不是 或 右子树不是 或 左右子树高度差超过121 if( leftdepth == -1 || rightdepth == -1 || abs(leftdepth-rightdepth) > 1 ) return -1;22 return max(leftdepth, rightdepth)+1;23 }24 };
Balanced Binary Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。