题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
代码
左子树和右子树高度差不得超过1 即为平衡二叉树;
public class Solution {public boolean IsBalanced_Solution(TreeNode root) {if (root == null) {return true;}int left=depth(root.left);int right=depth(root.right);int diff=Math.abs(left-right);if (diff>1){return false;}return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);}private int depth(TreeNode root) {if (root == null) {return 0;}int left = depth(root.left);int right = depth(root.right);return Math.max(left, right) + 1;}}
class Solution {public:bool IsBalanced_Solution(TreeNode *pRoot) {if (pRoot == nullptr) {return true;}int left = depth(pRoot->left);int right = depth(pRoot->right);if (abs(left - right) > 1) {return false;}return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);}public:int depth(TreeNode *root) {if (root == nullptr) {return 0;}int left = depth(root->left);int right = depth(root->right);return max(left, right) + 1;}};
