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.
题意:实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过1.
解法一:根据题意有一种解法,即直接递归访问整颗树,计算每个节点两棵子树的高度。但效率不高,这代码会递归访问每个结点的整棵子树,也就是说getHeight函数会反复调用计算同一个结点的高度。算法复杂度为O(NlogN);
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int getHeight(TreeNode *root) { if(root == NULL) return 0; return max(getHeight(root->left),getHeight(root->right)) +1 ; } bool isBalanced(TreeNode *root) { if(root == NULL) return false; int heightDiff = getHeight(root->left) - getHeight(root->right); if(abs(heightDiff) > 1) return false; else return isBalanced(root->left) && isBalanced(root->right); } };
解法二:根据解法一思路,我们可以删减部分getHeight的调用,仔细查看getHeight函数,你会发现getHeight不仅可以检查高度,还能检查这棵树是否平衡。那么我们发现子树不平衡时直接返回-1不就可以了嘛。
改进后的算法会从根结点递归检测每棵子树的高度。通过checkHeight方法,以递归方式获取每个结点左右子树的高度,若子树平衡,则返回该子树的实际高度。若子树不平衡,则返回-1。代码复杂度:O(N)时间和O(H)的空间,其中H为树的高度。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int checkHeight(TreeNode *root) { if(root == NULL) return 0; int leftHeight = checkHeight(root->left); if(leftHeight == -1) return -1; int rightHeight = checkHeight(root->right); if(rightHeight == -1) return -1; int heightDiff = leftHeight - rightHeight; if(abs(heightDiff) > 1) return -1; else return max(leftHeight,rightHeight)+1; } bool isBalanced(TreeNode *root) { if(checkHeight(root) == -1) return false; else return true; } };