Day 18 二叉树
513. 找树左下角的值
一眼层序遍历
层序遍历
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
if (!root) return -1;
queue<TreeNode*> que;
que.push(root);
int target;
while (!que.empty())
{
int len = que.size();
for (int i = 0; i < len; ++i)
{
TreeNode *cur = que.front();
que.pop();
if (i == 0)
{
target = cur->val;
}
if (cur->left) que.push(cur->left);
if (cur->right) que.push(cur->right);
}
}
return target;
}
};
112. 路径总和
回溯的方法文章来源:https://www.toymoban.com/news/detail-589722.html
class Solution {
int sum;
bool flag;
void helper(TreeNode *root, int targetSum)
{
if (!root) return;
sum += root->val;
if (!root->left && !root->right)
{
if (sum == targetSum)
{
flag = true;
}
}
else
{
if (root->left) helper(root->left, targetSum);
if (root->right) helper(root->right, targetSum);
}
sum -= root->val;
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
sum = 0;
flag = false;
helper(root, targetSum);
return flag;
}
};
106. 从中序与后序遍历序列构造二叉树
《剑指Offer》有“从前序与中序遍历序列构造二叉树”的讲解,这里把前序换成后序,应该是差不多的思路文章来源地址https://www.toymoban.com/news/detail-589722.html
class Solution {
TreeNode *build(
vector<int> &inorder, int startInorder, int endInorder,
vector<int> &postorder, int startPostorder, int endPostorder)
{
if (startInorder >= endInorder) return nullptr;
int targetVal = postorder[endPostorder - 1], idx = -1;
TreeNode *root = new TreeNode(targetVal);
for (int i = startInorder; i < endInorder; ++i)
{
if (inorder[i] == targetVal)
{
idx = i;
}
}
int leftLen = idx - startInorder;
root->left = build(inorder, startInorder, idx, postorder, startPostorder, startPostorder + leftLen);
root->right = build(inorder, idx + 1, endInorder, postorder, startPostorder + leftLen, endPostorder - 1);
return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode *root = build(inorder, 0, inorder.size(), postorder, 0, postorder.size());
return root;
}
};
到了这里,关于算法刷题Day18 找树左下角的值+路径总和+从中序与后序遍历构造二叉树的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!