PROBLEM

剑指 Offer 55 - II. 平衡二叉树

难度 简单

MY ANSWER

遍历每个节点获得深度,判断是否平衡。时间复杂度O(nlogn),空间复杂度O(n)。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int depth(TreeNode* root) {
if(!root) {
return 0;
}
else {
return max(depth(root->left), depth(root->right)) + 1;
}
}

bool isBalanced(TreeNode* root) {
if(!root) {
return true;
}
bool tmp = isBalanced(root->left) && isBalanced(root->right);
if(depth(root->left) - depth(root->right) > 1 || depth(root->right) - depth(root->left) > 1 ) {
return false;
}
return tmp;
}
};

BETTER SOLUTION

上面做法计算深度重复了,因此对二叉树做后序遍历,从底至顶返回子树深度,可以减少时间复杂度到O(n)。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int recur(TreeNode* root) {
if(!root) {
return 0;
}
int l = recur(root->left);
int r = recur(root->right);
if(l - r > 1 || r - l > 1 || l == -1 || r == -1) {
return -1;
}
else {
return max(l, r) + 1;
}
}

bool isBalanced(TreeNode* root) {
return recur(root) != -1;
}
};

SUMMARY

  • 掌握递归计算树的深度。
  • 理解后序遍历从底向上的性质,利用后序遍历的性质将儿子的信息传递给父亲。