Leetcode110. Balanced Binary Tree

xiaoxiao2021-02-28  111

110. Balanced Binary Tree

1、原题

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.

2、题意与解析

这道题目的意思很简单,就是让我们判断一个二叉树是不是一个平衡二叉树。               在这里我的思路是通过递归判断每一层的左右自树的高度。进行判断。具体看代码。

3、代码

int getHeight(TreeNode* root) { if (root == null) { return 0; } //求左右子树的高度 int l = getHeight(root->left); int r = getHeight(root->right); //当其子树中存在不平衡的部分或左右子树不平衡 if (abs(l - r) > 1 || l == -2 || r == -2) { return -2; } return max(l,r) + 1; } bool isBalanced(TreeNode* root) { if (root == null) { return true; } return getHeight(root) != -2; }
转载请注明原文地址: https://www.6miu.com/read-17510.html

最新回复(0)