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.
错误的思路(o(N2)时间复杂度):
写一个函数a,用递归遍历的方法,用于计算当前结点的高。
主函数从根节点开始,调用a计算其左子结点和右子结点高差值(×N),如果大于1则返回false,如果小于等于1则继续以左子结点和右子节点分别为根(×N),测试其平衡性;
正确的思路(o(N)时间复杂度):
错误的思路没有正确理解递归。判断平衡二叉树的条件是:①左子树是平衡的;②右子树是平衡的;③左子树和右子树的深度相差不超过1;
因此每一层递归只需要做两件事,判断左右子树是否平衡,判断左右子树深度差。
这样一来,遍历一遍即可获得判定结果。
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 int dep = 0; 14 return checkBalance(root, &dep); 15 } 16 17 bool checkBalance(TreeNode *node, int *dep) { 18 if (node == NULL) 19 return true; 20 21 int leftDep = 0; 22 int rightDep = 0; 23 bool leftBalance = checkBalance(node->left, &leftDep); 24 bool rightBalance = checkBalance(node->right, &rightDep); 25 26 *dep = max(leftDep, rightDep) + 1; 27 28 return leftBalance && rightBalance && 29 (abs(rightDep - leftDep) <= 1); 30 } 31 };
时间: 2024-10-22 03:13:22