Balanced Binary Tree – LeetCode 110 Problem Description 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.
Answer Original Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution {public : int depth (TreeNode *node) { if (!node) return 0 ; return 1 + max (depth (node->left),depth (node->right)); } bool isBalanced (TreeNode* root) { if (!root) return true ; return abs (depth (root->left) - depth (root->right)) <= 1 && isBalanced (root->left) && isBalanced (root->right); } };
思路 依旧是DFS递归解,因为BFS在此处需要连续两层状态信息所以不好用,时间复杂度$O(n^2)$,空间复杂度$O(n)$。 耗时$9$ ms,排名$74.26\%$
Better 思路 简化版本,使用-1作为状态码,在计算深度的过程中检测是否平衡,有效避免额外运算。时间复杂度$O(n)$,空间复杂度$O(n)$。 耗时$9$ ms,排名$74.26\%$
Code 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 class Solution {public : bool isBalanced (TreeNode *root) { if (checkDepth (root) == -1 ) return false ; else return true ; } int checkDepth (TreeNode *root) { if (!root) return 0 ; int left = checkDepth (root->left); if (left == -1 ) return -1 ; int right = checkDepth (root->right); if (right == -1 ) return -1 ; int diff = abs (left - right); if (diff > 1 ) return -1 ; else return 1 + max (left, right); } };