传送门
nowcoder
leetcode
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。在这里,只需要考虑其平衡性,不需要考虑其是不是排序二叉树。
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过 1,并且左右两个子树都是一棵平衡二叉树。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
class Solution { public: bool IsBalanced_Solution(TreeNode* pRoot) { if (pRoot == nullptr) return true; return abs(maxDepth(pRoot->left) - maxDepth(pRoot->right)) <= 1 && IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right); }
int maxDepth(TreeNode* node) { if (node == nullptr) return 0; return 1 + max(maxDepth(node->left), maxDepth(node->right)); } };
class Solution { public: bool IsBalanced_Solution(TreeNode* pRoot) { if (pRoot == nullptr) return true; return getDepth(pRoot) != -1; }
int getDepth(TreeNode* node) { if (node == nullptr) return 0;
int leftDepth = getDepth(node->left); if (leftDepth == -1) return -1; int rightDepth = getDepth(node->right); if (rightDepth == -1) return -1;
if (abs(leftDepth - rightDepth) > 1) return -1; else return 1 + max(leftDepth, rightDepth); } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
class Solution { public: bool isBalanced(TreeNode* root) { if (root == nullptr) return true; return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right); }
int maxDepth(TreeNode* node) { if (node == nullptr) return 0; return 1 + max(maxDepth(node->left), maxDepth(node->right)); } };
class Solution { public: bool isBalanced(TreeNode* root) { if (root == nullptr) return true; return getDepth(root) != -1; }
int getDepth(TreeNode* node) { if (node == nullptr) return 0;
int leftDepth = getDepth(node->left); if (leftDepth == -1) return -1; int rightDepth = getDepth(node->right); if (rightDepth == -1) return -1; if (abs(leftDepth - rightDepth) > 1) return -1; else return 1 + max(leftDepth, rightDepth); } };
|