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. 路径总和
回溯的方法
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》有“从前序与中序遍历序列构造二叉树”的讲解,这里把前序换成后序,应该是差不多的思路
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;
}
};