按照下图分析非平衡二叉树的情况
int height(struct TreeNode* root)
{
// 有一个子树不平衡则整个树肯定不平衡
if (!root) return 0;
int left = height(root->left);
if (left == -1) return -1;
int right = height(root->right);
if (right == -1) return -1;
int result;
// 子树平衡的前提下判断高度差
if (fabs(right - left) > 1){
result = -1;
}else {
result = 1 + fmax(left, right);
}
return result;
}
bool isBalanced(struct TreeNode* root){
return height(root) >= 0;
}
似乎真的是卡哥说的那样,我做出来了,但是不知道自己用的是回溯,好像知道那里是回溯的点,但是表达不清,只可意会那种
画个图吧,画个图就清楚了,二刷的时候尽量贴个图上来
void construct_paths(struct TreeNode* root, char** paths, int* returnSize, int* sta, int top)
{
if (root)
{
if (!root->left && !root->right) //左右为空,即叶子结点
{
char* tmp = (char*)malloc(100);
int len = 0;
for (int i=0; i<top; i++)
{
// tmp不变,通过+len改变存入的地址
len += sprintf(tmp+len, "%d->", sta[i]); //sprintf成功时返回字符总数,不包含空字符
}
sprintf(tmp+len, "%d", root->val);//输出最后一个数字
paths[(*returnSize)++] = tmp;
}else {
sta[top++] = root->val;
construct_paths(root->left, paths, returnSize, sta, top);
construct_paths(root->right, paths, returnSize, sta, top);
}
}
}
char ** binaryTreePaths(struct TreeNode* root, int* returnSize){
char** paths = (char**)malloc(sizeof(char*) * 100);
*returnSize = 0;
int sta[1001]; //用来存放每一个路径每个节点的值
construct_paths(root, paths, returnSize, sta, 0);
return paths;
}
二刷,三刷都不为过
int sumOfLeftLeaves(struct TreeNode* root){
if (!root) return 0;
if (!root->left && !root->right) return 0;
int left = sumOfLeftLeaves(root->left);
// 由于是左叶子节点,深度未知,所以还需要判断是不是叶子节点,只有是叶子节点时才赋值
if (root->left && !root->left->left && !root->left->right)
{
left = root->left->val;
}
int right = sumOfLeftLeaves(root->right);
int sum = left + right;
return sum;
}