/* 题目: 判断二叉树是否为平衡二叉树。 */ /* 思路: 判断二叉树的左子树和右子树高度相差是否为1. */ #include<iostream> #include<cstring> #include<vector> #include<algorithm> #include<map> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; bool isBalanced(TreeNode* pRoot,int &depth){ if(pRoot == nullptr){ return true; } int leftDepth = 0; int rightDepth = 0; //若左右子树都平衡 if(isBalanced(pRoot->left,leftDepth) && isBalanced(pRoot->right,rightDepth)){ int diff = leftDepth - rightDepth; if(diff <= 1 && diff >= -1){ depth = max(leftDepth,rightDepth) + 1; return true; } } return false; } bool isBalanced(TreeNode* pRoot){ int depth = 0; return isBalanced(pRoot,depth); } int main(){ TreeNode* node = new TreeNode(1); TreeNode* node1 = new TreeNode(2); TreeNode* node2 = new TreeNode(3); TreeNode* node3 = new TreeNode(4); TreeNode* node4 = new TreeNode(5); TreeNode* node5 = new TreeNode(6); TreeNode* node6 = new TreeNode(7); node->left = node1; node->right = node2; node1->left = node3; node1->right = node4; node2->right = node5; node4->left = node6; cout<<isBalanced(node); }