代码随想录算法训练营第十八天_第六章_二叉树 | 513.找树左下角的值、112. 路径总和 113.路径总和Ⅱ、106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树

LeetCode 513.找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

视频讲解https://www.bilibili.com/video/BV1424y1Z7pn文章讲解https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html#%E8%A7%86%E9%A2%91%E8%AE%B2%E8%A7%A3

  • 思路:最底层节点👉深度最大的叶子节点
    • 递归:用变量 maxDepth 记录遍历过的节点的最大深度
    1. 参数、返回值:当前访问节点,该节点深度        不需要返回值
      int maxDepth = INT_MIN;   // 全局变量 记录最大深度
      int result;       // 全局变量 最大深度最左节点的数值
      void traversal(TreeNode* root, int depth)
    2. 终止条件:遇到叶子节点(看其 depth 能否更新 maxDepth,若能则记录该节点值),返回
      if (root->left == NULL && root->right == NULL) {
          if (depth > maxDepth) {
              maxDepth = depth;           // 更新最大深度
              result = root->val;   // 最大深度最左面的数值
          }
          return;
      }
    3. 单层递归逻辑:先左后右,非空才进行下一层递归
    • 迭代:层序遍历,result 记录每层最左边节点的值,最终 result 即为最底层最左边节点值
  • 代码: 
// 递归
class Solution {
public:
    int maxDepth = INT_MIN;
    int result;
    void traversal(TreeNode* root, int depth) {
        if (root->left == NULL && root->right == NULL) {
            if (depth > maxDepth) {
                maxDepth = depth;
                result = root->val;
            }
            return;
        }
        if (root->left) {
            traversal(root->left, depth + 1); // 隐藏着回溯
        }
        if (root->right) {
            traversal(root->right, depth + 1); // 隐藏着回溯
        }
        return;
    }
    int findBottomLeftValue(TreeNode* root) {
        traversal(root, 1);
        return result;
    }
};
// 迭代
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        int result = 0;
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (i == 0) result = node->val; // 记录每行第一个元素
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return result;
    }
};

LeetCode 112. 路径总和                bool 

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true;否则,返回 false

视频讲解https://www.bilibili.com/video/BV19t4y1L7CR/?spm_id_from=333.788&vd_source=f98f2942b3c4cafea8907a325fc56a48文章讲解https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html#%E8%A7%86%E9%A2%91%E8%AE%B2%E8%A7%A3

  • 思路:
    • 递归:找一条符合条件的路径,所以递归函数需要返回值,及时返回
    1. 确定递归函数的参数和返回类型(bool):需要二叉树的根节点,还需要一个计数器,这个计数器用来计算二叉树的一条边之和是否正好是目标和,计数器为int型。
    2. 终止条件:
      if (!cur->left && !cur->right && count == 0) return true; // 遇到叶子节点,并且计数为0
      if (!cur->left && !cur->right) return false; // 遇到叶子节点而没有找到合适的边,直接返回
    3. 单层递归逻辑:如果递归函数返回true,说明找到了合适的路径,应该立刻返回
      if (cur->left) { // 左 (空节点不遍历)
          // 遇到叶子节点返回true,则直接返回true
          if (traversal(cur->left, count - cur->left->val)) return true; // 注意这里有回溯的逻辑
      }
      if (cur->right) { // 右 (空节点不遍历)
          // 遇到叶子节点返回true,则直接返回true
          if (traversal(cur->right, count - cur->right->val)) return true; // 注意这里有回溯的逻辑
      }
      return false;

      回溯隐藏在 traversal(cur->left, count - cur->left->val)中,count 值没变。

    • 迭代:栈不仅需要存储 节点,还需要存储 从根节点到当前节点的路径和
      // pair<节点指针,路径数值>
      pair<TreeNode*, int>
  • 代码:
// 递归
class Solution {
private:
    // count 表示 从cur的孩子节点到叶子节点 需要匹配的路径和
    bool traversal(TreeNode* cur, int count) {
        if (!cur->left && !cur->right && count == 0) return true; // 遇到叶子节点,并且计数为0
        if (!cur->left && !cur->right) return false; // 遇到叶子节点直接返回

        if (cur->left) { // 左
            count -= cur->left->val; // 递归,处理节点;
            if (traversal(cur->left, count)) return true;
            count += cur->left->val; // 回溯,撤销处理结果
        }
        if (cur->right) { // 右
            count -= cur->right->val; // 递归,处理节点;
            if (traversal(cur->right, count)) return true;
            count += cur->right->val; // 回溯,撤销处理结果
        }
        return false;
    }

public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == NULL) return false;
        return traversal(root, targetSum - root->val);
    }
};
// 精简版:targetSum 表示 从root到叶子节点 需要匹配的路径和
class solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == null) return false;
        // 直接与叶子节点的值比较即可
        if (!root->left && !root->right && targetSum == root->val) {
            return true;
        }
        // 左孩子、右孩子的递归,传入的需匹配路径和一致,都只需减去 root->val
        return haspathsum(root->left, targetSum - root->val) || haspathsum(root->right, targetSum - root->val);
    }
};
// 迭代
class solution {
public:
    bool haspathsum(TreeNode* root, int targetSum) {
        if (root == null) return false;
        // 此时栈里要放的是pair<节点指针,路径数值>
        stack<pair<TreeNode*, int>> st;
        st.push(pair<TreeNode*, int>(root, root->val));
        while (!st.empty()) {
            pair<TreeNode*, int> node = st.top();
            st.pop();
            // 如果该节点是叶子节点了,同时该节点的路径数值等于targetSum,那么就返回true
            if (!node.first->left && !node.first->right && targetSum == node.second) return true;

            // 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
            if (node.first->right) {
                st.push(pair<TreeNode*, int>(node.first->right, node.second + node.first->right->val));
            }

            // 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
            if (node.first->left) {
                st.push(pair<TreeNode*, int>(node.first->left, node.second + node.first->left->val));
            }
        }
        return false;
    }
};
// 迭代:这样写更清楚
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        // <非空节点,根节点到当前节点的路径和>
        stack<pair<TreeNode*, int>> st;
        if (root == NULL) return false;
        st.push({root, root->val});
        while (!st.empty()) {
            TreeNode* node = st.top().first;
            int pathSum = st.top().second;
            st.pop();
            // 叶子节点
            if (node->left == NULL && node->right == NULL && pathSum == targetSum) return true;
            if (node->right) {
                st.push({node->right, pathSum + node->right->val});
            }
            if (node->left) {
                st.push({node->left, pathSum + node->left->val});
            }
        }
        return false;
    }
};

LeetCode 113.路径总和Ⅱ                 vector<vector<int>>

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。 

  • 思路:
    • 递归:找所有路径,所以递归函数不需要返回值
    • 迭代:LeetCode 257.二叉树的所有路径
      • pathST 从 stack<string> 换成 stack<vector<int>>
      • 若弹出的 node 为叶子节点,遍历其 path 计算出路径和 sum,与 targetSum 比较,相等则计入结果集
  • 代码:
// 递归
class solution {
private:
    vector<vector<int>> result;
    vector<int> path;
    // 递归函数不需要返回值,因为我们要遍历整个树
    void traversal(treenode* cur, int count) {
        if (!cur->left && !cur->right && count == 0) { // 遇到了叶子节点且找到了和为sum的路径
            result.push_back(path);
            return;
        }

        if (!cur->left && !cur->right) return ; // 遇到叶子节点而没有找到合适的边,直接返回

        if (cur->left) { // 左 (空节点不遍历)
            path.push_back(cur->left->val);
            count -= cur->left->val;
            traversal(cur->left, count);    // 递归
            count += cur->left->val;        // 回溯
            path.pop_back();                // 回溯
        }
        if (cur->right) { // 右 (空节点不遍历)
            path.push_back(cur->right->val);
            count -= cur->right->val;
            traversal(cur->right, count);   // 递归
            count += cur->right->val;       // 回溯
            path.pop_back();                // 回溯
        }
        return ;
    }

public:
    vector<vector<int>> pathsum(treenode* root, int targetSum) {
        result.clear();
        path.clear();
        if (root == null) return result;
        path.push_back(root->val); // 把根节点放进路径
        traversal(root, targetSum - root->val);
        return result;
    }
};

// 递归:自己习惯写法
class Solution {
public:
    vector<vector<int>> result;
    // 当前访问节点node(非空) 从node到叶子节点需要的路径和  传入node之前的路径
    void traversal(TreeNode* node, int pathValue, vector<int> path) {
        // 把node加到路径path上
        path.push_back(node->val);
        // 终止条件:叶子节点
        if (node->left == NULL && node->right == NULL) {
            if (node->val == pathValue) result.push_back(path);
            return;
        }
        if (node->left) {
            traversal(node->left, pathValue - (node->val), path);
        }
        if (node->right) {
            traversal(node->right, pathValue - (node->val), path);
        }
        return;
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        if (root) traversal(root, targetSum, vector<int>());
        return result;
    }
};
 // 迭代
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<vector<int>> result;
        stack<TreeNode*> treeST;    // 非空节点才入栈
        stack<vector<int>> pathST;
        if (root == NULL) return result;
        treeST.push(root);
        pathST.push({root->val});
        while (!treeST.empty()) {
            TreeNode* node = treeST.top();
            treeST.pop();
            vector<int> path = pathST.top();
            pathST.pop();
            // 若node为叶子节点
            if (node->left == NULL && node->right == NULL) {
                // 遍历path得到路径和
                int sum = 0;
                for (int i = 0; i < path.size(); ++i) {
                    sum += path[i];
                }
                if (sum == targetSum) result.push_back(path);
            }
            // 右
            if (node->right) {
                treeST.push(node->right);
                path.push_back(node->right->val);    // 更改了path
                pathST.push(path);
                path.pop_back();                        // 回溯
            }
            // 左
            if (node->left) {
                treeST.push(node->left);
                path.push_back(node->left->val);    // 更改了path
                pathST.push(path);
                path.pop_back();                        // 回溯
            }
        }
        return result;
    }
};

👆遍历二叉树 vs 构造二叉树👇

LeetCode 106.从中序与后序遍历序列构造二叉树

 给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

视频讲解https://www.bilibili.com/video/BV1vW4y1i7dn文章讲解https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E6%80%9D%E8%B7%AF

  • 思路:后序最后一个👉根👉用根切割中序👉根据中序分割区间长度切割后序👉递归
    • 具体步骤:
    1. 如果数组大小为零的话,说明是空节点了;
    2. 如果不为空,那么取后序数组最后一个元素作为节点元素;
    3. 找到后序数组最后一个元素在中序数组的位置,作为切割点;
    4. 切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组);
      // 左闭右开区间:[0, delimiterIndex)
      vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
      // [delimiterIndex + 1, end)
      vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end() );
    5. 切割后序数组,切成后序左数组和后序右数组
      // postorder 舍弃末尾元素,因为这个元素就是中间节点,已经用过了
      postorder.resize(postorder.size() - 1);
      
      // 左闭右开,注意这里使用了左中序数组大小作为切割点:[0, leftInorder.size)
      vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
      // [leftInorder.size(), end)
      vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end());
    6. 递归处理左区间和右区间。
      // 整体框架
      TreeNode* traversal (vector<int>& inorder, vector<int>& postorder) {
      
          // 第一步
          if (postorder.size() == 0) return NULL;
      
          // 第二步:后序遍历数组最后一个元素,就是当前的中间节点
          int rootValue = postorder[postorder.size() - 1];
          TreeNode* root = new TreeNode(rootValue);
      
          // 叶子节点
          if (postorder.size() == 1) return root;
      
          // 第三步:找切割点
          int delimiterIndex;
          for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
              if (inorder[delimiterIndex] == rootValue) break;
          }
      
          // 第四步:切割中序数组,得到 中序左数组和中序右数组
          // 第五步:切割后序数组,得到 后序左数组和后序右数组
      
          // 第六步
          root->left = traversal(中序左数组, 后序左数组);
          root->right = traversal(中序右数组, 后序右数组);
      
          return root;
      }
  • 代码: 
class Solution {
private:
    TreeNode* traversal (vector<int>& inorder, vector<int>& postorder) {
        if (postorder.size() == 0) return NULL;

        // 后序遍历数组最后一个元素,就是当前的中间节点
        int rootValue = postorder[postorder.size() - 1];
        TreeNode* root = new TreeNode(rootValue);

        // 叶子节点
        if (postorder.size() == 1) return root;

        // 找到中序遍历的切割点
        int delimiterIndex;
        for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }

        // 切割中序数组
        // 左闭右开区间:[0, delimiterIndex)
        vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
        // [delimiterIndex + 1, end)
        vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end() );

        // postorder 舍弃末尾元素
        postorder.resize(postorder.size() - 1);

        // 切割后序数组
        // 依然左闭右开,注意这里使用了左中序数组大小作为切割点
        // [0, leftInorder.size)
        vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
        // [leftInorder.size(), end)
        vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end());

        root->left = traversal(leftInorder, leftPostorder);
        root->right = traversal(rightInorder, rightPostorder);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return NULL;
        return traversal(inorder, postorder);
    }
};
// 优化版
class Solution {
private:
    // 中序区间:[inorderBegin, inorderEnd),后序区间[postorderBegin, postorderEnd)
    TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& postorder, int postorderBegin, int postorderEnd) {
        if (postorderBegin == postorderEnd) return NULL;

        int rootValue = postorder[postorderEnd - 1];
        TreeNode* root = new TreeNode(rootValue);

        if (postorderEnd - postorderBegin == 1) return root;

        int delimiterIndex;
        for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }
        // 切割中序数组
        // 左中序区间,左闭右开[leftInorderBegin, leftInorderEnd)
        int leftInorderBegin = inorderBegin;
        int leftInorderEnd = delimiterIndex;
        // 右中序区间,左闭右开[rightInorderBegin, rightInorderEnd)
        int rightInorderBegin = delimiterIndex + 1;
        int rightInorderEnd = inorderEnd;

        // 切割后序数组
        // 左后序区间,左闭右开[leftPostorderBegin, leftPostorderEnd)
        int leftPostorderBegin =  postorderBegin;
        int leftPostorderEnd = postorderBegin + (delimiterIndex - inorderBegin); // 终止位置是 需要加上 中序区间的大小size
        // 右后序区间,左闭右开[rightPostorderBegin, rightPostorderEnd)
        int rightPostorderBegin = postorderBegin + (delimiterIndex - inorderBegin);
        int rightPostorderEnd = postorderEnd - 1; // 排除最后一个元素,已经作为节点了

        root->left = traversal(inorder, leftInorderBegin, leftInorderEnd,  postorder, leftPostorderBegin, leftPostorderEnd);
        root->right = traversal(inorder, rightInorderBegin, rightInorderEnd, postorder, rightPostorderBegin, rightPostorderEnd);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return NULL;
        // 左闭右开的原则
        return traversal(inorder, 0, inorder.size(), postorder, 0, postorder.size());
    }
};

LeetCode 105.从前序与中序遍历序列构造二叉树

  • 思路:前序第一个👉根👉用根切割中序👉根据中序分割区间长度切割前序👉递归
  • 代码: 
// 优化版
class Solution {
private:
        TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& preorder, int preorderBegin, int preorderEnd) {
        if (preorderBegin == preorderEnd) return NULL;

        int rootValue = preorder[preorderBegin]; // 注意用preorderBegin 不要用0
        TreeNode* root = new TreeNode(rootValue);

        if (preorderEnd - preorderBegin == 1) return root;

        int delimiterIndex;
        for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }
        // 切割中序数组
        // 中序左区间,左闭右开[leftInorderBegin, leftInorderEnd)
        int leftInorderBegin = inorderBegin;
        int leftInorderEnd = delimiterIndex;
        // 中序右区间,左闭右开[rightInorderBegin, rightInorderEnd)
        int rightInorderBegin = delimiterIndex + 1;
        int rightInorderEnd = inorderEnd;

        // 切割前序数组
        // 前序左区间,左闭右开[leftPreorderBegin, leftPreorderEnd)
        int leftPreorderBegin =  preorderBegin + 1;
        int leftPreorderEnd = preorderBegin + 1 + delimiterIndex - inorderBegin; // 终止位置是起始位置加上中序左区间的大小size
        // 前序右区间, 左闭右开[rightPreorderBegin, rightPreorderEnd)
        int rightPreorderBegin = preorderBegin + 1 + (delimiterIndex - inorderBegin);
        int rightPreorderEnd = preorderEnd;

        root->left = traversal(inorder, leftInorderBegin, leftInorderEnd,  preorder, leftPreorderBegin, leftPreorderEnd);
        root->right = traversal(inorder, rightInorderBegin, rightInorderEnd, preorder, rightPreorderBegin, rightPreorderEnd);

        return root;
    }

public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if (inorder.size() == 0 || preorder.size() == 0) return NULL;

        // 参数坚持左闭右开的原则
        return traversal(inorder, 0, inorder.size(), preorder, 0, preorder.size());
    }
};

⭐思考:

前序和中序可以唯一确定一棵二叉树。

后序和中序可以唯一确定一棵二叉树。

那么前序和后序可不可以唯一确定一棵二叉树呢?

前序都是:1,2,3;后序都是:3,2,1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值