day18打卡
- 递归法
- 时间复杂度:O(N),空间复杂度:O(N)
class Solution {
public:
int maxDepth = INT_MIN;
int ret;
int findBottomLeftValue(TreeNode* root) {
dfs(root, 0);
return ret;
}
void dfs(TreeNode* root, int depth)
{
if(root == nullptr) return;
depth++;
dfs(root->left, depth);
dfs(root->right, depth);
if(depth > maxDepth)
{
maxDepth = depth;
ret = root->val;
return;
}
}
};
- 迭代法
- 时间复杂度:O(N),空间复杂度:O(N)
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int ret = 0;
queue<TreeNode*> q;
if(root != nullptr) q.push(root);
while(!q.empty())
{
int size = q.size();
for(int i = 0; i < size; i++)
{
TreeNode* top = q.front();
q.pop();
//先push右节点,再push左节点,这样保证最后一个节点是左节点即可
if(top->right) q.push(top->right);
if(top->left) q.push(top->left);
ret = top->val;
}
}
return ret;
}
};
- 递归
- 时间复杂度:O(N),空间复杂度:O(N)
class Solution {
public:
bool dfs(TreeNode* root, int targetSum, int sum)
{
if(root == nullptr) return false;
if(root->left == nullptr && root->right == nullptr)
return (sum + root->val) == targetSum;
return dfs(root->left, targetSum, sum + root->val) ||
dfs(root->right, targetSum, sum + root->val);
}
bool hasPathSum(TreeNode* root, int targetSum) {
int sum = 0;
return dfs(root, targetSum, sum);
}
};
-
迭代法
-
时间复杂度:O(N),空间复杂度:O(N)
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return false;
queue<TreeNode*> q;
queue<int> qVal;
q.push(root);
qVal.push(root->val);
while(!q.empty())
{
TreeNode* top = q.front();
int tmp = qVal.front();
q.pop();
qVal.pop();
if(top->left == nullptr && top->right == nullptr)
{
if(tmp == targetSum) return true;
else continue;
}
if(top->left)
{
q.push(top->left);
qVal.push(top->left->val + tmp);
}
if(top->right)
{
q.push(top->right);
qVal.push(top->right->val + tmp);
}
}
return false;
}
};
思路后面补。
class Solution {
public:
TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,
int inBegin, int inEnd, int poBegin, int poEnd)
{
if(inBegin > inEnd) return nullptr;
int k = postorder[poEnd];
TreeNode* root = new TreeNode(k);
for(int i = 0; i < inorder.size(); i++)
{
if(k == inorder[i])
{
root->left = _buildTree(inorder, postorder, inBegin, i-1,
poBegin, poBegin + i-1-inBegin);
root->right = _buildTree(inorder, postorder, i+1, inEnd,
poBegin+i-1-inBegin+1, poEnd-1);
break;
}
}
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return _buildTree(inorder, postorder,
0, inorder.size()-1, 0, postorder.size()-1);
}
};