代码随想录算法训练营day18 | LeetCode 513. 找树左下角的值 112. 路径总和 106. 从中序与后序遍历序列构造二叉树

513. 找树左下角的值(题目链接:力扣

思路:典型的二叉树便利题,可以考录用递归或者迭代,递归的话就是正常的前序遍历或者中序遍历,但是都需要定义一个全局变量记录深度,当每第一次达到最大深度时(遍历到叶子节点的时候)记录该节点的值。迭代就是用层序便利了,每次拿出每层第一个节点的值记录下来,当层序遍历完,最后一次赋的值也就是数左下角的值了。

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(): val(0), left(NULL), right(NULL){}
}

int depth = 0;
int result = 0;

void getDepth(TreeNode* root, int tmpDepth){
    if(root->left == NULL && root->right == NULL){
        if(tmpDepth > depth){
            result = root->val;
            depth = tmpDepth;
        }
    }
    if(root->left){
        getDepth(root->left, tmpDepth + 1);
    } 
    if(root->right){
        getDepth(root->right, tmpDepth + 1);
    }
}

int findBottomLeftValue(TreeNode* root) {
    getDepth(root, 1);
    return result;
}
int findBottomLeftValue(TreeNode* root) {
    int result = 0;
    queue<TreeNode*> que;
    que.push(root);
    while(!que.empty()){
        TreeNode* node = que.front();
        que.pop();
        result = node->val;
        int size = que.size();
        if(node->left) que.push(node->left);
        if(node->right) que.push(node->right);
        for(int i=0; i<size; i++){
            node = que.front();
            que.pop();
            if(node->left) que.push(node->left);
            if(node->right) que.push(node->right);
        }
    }
    return result;
}

112. 路径总和(题目链接:力扣

思路:典型的回溯法,首先讲递归的做法,每次迭代要传给子树的参数包括节点指针、到本节点为止的值的和,遍历到叶子结点时进行判断。(这种做法也可以不需要传num,直接每次吧targetSum减去本节点的值再传给子树,这样可以少一个参数,而且也不用另外写一个函数)

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(): val(0), left(NULL), right(NULL){}
}

bool flag = false;

void traversal(TreeNode* root, int num, int targetSum){
    if(root->left == NULL && root->right == NULL){
        if(num + root->val == targetSum) flag = true;
    }
    if(root->left) traversal(root->left, root->val + num, targetSum);
    if(root->right) traversal(root->right, root->val + num, targetSum);
}

bool hasPathSum(TreeNode* root, int targetSum) {
    if(root == NULL) return false;
    traversal(root, 0, targetSum);
    return flag;
}

第二种迭代的做法,其实有点画蛇添足,比递归做法要复杂不少,但也算锻炼对树的遍历算法练习。因为节点指针和暂时和值必不可少,所以需要往stack里面push进pair<TreeNode*, int>才行,然后还是碰到节点指针进行判断。

bool hasPathSum(TreeNode* root, int targetSum) {
    if(root == NULL) return false;
    stack<pair<TreeNode*, int>> st;
    st.push(pair<TreeNode*, int>(root, 0));
    while(!st.empty()){
        pair<TreeNode*, int> node = st.top();
        st.pop();
        if(node.first->left == NULL && node.first->right == NULL && node.second + node.first->val == targetSum) return true;
        if(node.first->right) st.push(pair<TreeNode*, int>(node.first->right, node.second + node.first->val));
        if(node.first->left) st.push(pair<TreeNode*, int>(node.first->left, node.second + node.first->val));
    }
}

leetcode上还有一道求路径和的题和这个差不多力扣

106. 从中序与后序遍历序列构造二叉树(题目链接:力扣

思路:又是一道经典的二叉树构造题,注意前后序遍历和中序遍历的规律即可。(tips:如果用到数组做形参,就可以在函数体内不再构造新数组)

TreeNode* traversal(vector<int>& inOrder, int inStart, int inEnd, vector<int>& postOrder, int postStart, int postEnd){
    int size = inEnd - inStart;
    if(size == 0) return NULL;
    TreeNode* root = new TreeNode(postOrder[postEnd - 1]);
    if(size == 1) return root;
    int rootIndex;
    for(rootIndex=inStart; rootIndex<inEnd; rootIndex++){
        if(inOrder[rootIndex] == root->val) break;
    }
    root->left = traversal(inOrder, inStart, rootIndex, postOrder, postStart, postStart+rootIndex-inStart);
    root->right = traversal(inOrder, rootIndex+1, inEnd, postOrder, postStart+rootIndex-inStart, postEnd-1);
    return root;
}

TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    return traversal(inorder, 0, inorder.size(), postorder, 0, postorder.size());
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,使得子数组的和大于等于给定的目标。这里可以使用滑动窗口的方法来解决问题。使用两个指针来表示滑动窗口的左边界和右边界,通过移动指针来调整滑动窗口的大小,使得滑动窗口中的元素的和满足题目要求。具体实现的代码如下: ```python def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 right = 0 ans = float('inf') total = 0 while right < len(nums): total += nums[right] while total >= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 right += 1 return ans if ans != float('inf') else 0 ``` 以上就是第二十二天的算法训练营的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_porter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值