一、题目
二、代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int depth_cal(TreeNode* root)
{
int i,j;
int return_depth=0;
queue<TreeNode*> range_first_tree_for_cal;
int queue_size_for_cal;
TreeNode* process_node_for_cal;
if(root!=nullptr)
{
range_first_tree_for_cal.push(root);
while(!range_first_tree_for_cal.empty())
{
return_depth++;
queue_size_for_cal=range_first_tree_for_cal.size();
for(i=0;i<queue_size_for_cal;i++)
{
process_node_for_cal=range_first_tree_for_cal.front();
range_first_tree_for_cal.pop();
//层序遍历每一个节点 传入函数计算节点的左右子树高度差
//std::cout<<" "<<process_node_for_cal->val;
if(process_node_for_cal->left) range_first_tree_for_cal.push(process_node_for_cal->left);
if(process_node_for_cal->right) range_first_tree_for_cal.push(process_node_for_cal->right);
}
}
}
return return_depth;
}
bool isBalanced(TreeNode* root)
{
int return_bool=1;
int i,j;
queue<TreeNode*> range_first_tree;
int queue_size;
TreeNode* process_node;
if(root !=nullptr)
{
range_first_tree.push(root);
while(!range_first_tree.empty())
{
queue_size=range_first_tree.size();
for(i=0;i<queue_size;i++)
{
process_node=range_first_tree.front();
range_first_tree.pop();
//层序遍历每一个节点 传入函数计算节点的左右子树高度差
//std::cout<<" "<<process_node->val;
if(abs(depth_cal(process_node->left)-depth_cal(process_node->right))>=2)
{
return_bool=0;
break;
}
if(process_node->left) range_first_tree.push(process_node->left);
if(process_node->right) range_first_tree.push(process_node->right);
}
if(return_bool==0) break;
}
}
return return_bool;
}
};