代码随想录算法训练营第十七天 [110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和 ]
一、110.平衡二叉树
链接: 代码随想录.
思路:判断左右节点的高度差是不是大于1,上一层的高度是他左子节点的高度和右子节点的高度最大值+1,因为需要一层一层向上传递高度,所以是后序遍历,左右中
做题状态:看解析后做出来了
class Solution
{
public:
bool isBalanced(TreeNode *root)
{
if (getHeight(root) == -1)
{
return false;
}
return true;
}
int getHeight(TreeNode *node)
{
if (node == nullptr)
{
return 0;
}
int leftHeight = getHeight(node->left);
int rightHeight = getHeight(node->right);
if (leftHeight == -1)
{
return -1;
}
if (rightHeight == -1)
{
return -1;
}
int result = 0;
if (abs(leftHeight - rightHeight) > 1)
{
result = -1;
}
else
{
result = max(leftHeight, rightHeight) + 1;
}
return result;
}
};
二、57. 二叉树的所有路径
链接: 代码随想录.
思路:回溯
做题状态:看解析后做出来了
class Solution
{
public:
vector<string> binaryTreePaths(TreeNode *root)
{
vector<string> result;
vector<int> path;
if (root == nullptr)
{
return result;
}
get_path(root, path, result);
return result;
}
void get_path(TreeNode *cur, vector<int> &path, vector<string> &result)
{
// 中
// 这里也是递归中单层逻辑
// 为什么要在这里加?
// 下面开始判断叶子节点,如果判断是叶子节点就会return
// 写在下面的话,叶子节点就没加进来
path.push_back(cur->val);
// 首先确定递归中结束的条件
if (cur->left == nullptr && cur->right == nullptr)
// 遇到叶子节点的时候开始处理终止逻辑
// 遇到叶子节点,说明找到一条路径了,要处理路径结果
{
string sPath;
for (int i = 0; i < path.size() - 1; i++)
{
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
// 再写递归中单层的逻辑
if (cur->left)
{
// 左
get_path(cur->left, path, result);
// 回溯
path.pop_back();
}
if (cur->right)
{
// 右
get_path(cur->right, path, result);
// 回溯
path.pop_back();
}
}
};
三、404.左叶子之和
链接: 代码随想录.
思路:弄清左叶子的定义,找左叶子需要找到他的父节点,否则无法判断叶子节点是不是其父节点的左节点
做题状态:看解析后做出来了
class Solution
{
public:
int sumOfLeftLeaves(TreeNode *root)
{
return get_left(root);
}
int get_left(TreeNode *node)
{
// 递归的结束条件
if (node == nullptr)
{
return 0;
}
if (node->left == nullptr && node->right == nullptr)
{
return 0;
}
// 左
int leftNum = get_left(node->left);
// 收集结果
if (node->left && node->left->left == nullptr && node->left->right == nullptr)
{
leftNum = node->left->val;
}
// 右
int rightNum = get_left(node->right);
// 中
return leftNum + rightNum;
}
};