解法:
平衡二叉樹是一種特殊的二叉樹,它滿足以下兩個條件:
- 左子樹和右子樹的高度差不超過1(即,左右子樹高度差的絕對值不超過1)。
- 左子樹和右子樹都是平衡二叉樹。
后序遍歷過程中每次判斷左右子樹高度差和1的關系即可
#include<iostream>
using namespace std;
struct treeNode {char val;treeNode* left, * right;treeNode(char x) :val(x), left(NULL), right(NULL) {};
};
treeNode* buildtree() {char ch;cin >> ch;if (ch == '#') return NULL;treeNode* root = new treeNode(ch);root->left = buildtree();root->right = buildtree();return root;
}
bool f = false;
int dfs(treeNode* r) {if (r == NULL) return 0;int lh = dfs(r->left);int rh = dfs(r->right);if (abs(lh - rh) > 1) f = true;return max(lh, rh) + 1;
}
int main() {treeNode* root = buildtree();if (root == NULL) cout << "yes!";else {dfs(root);if (f) cout << "no!";else cout << "yes!";}return 0;
}