《录鼎记》第十六章——得慢慢看,不然看不懂了

今日内容

  • 513.找树左下角的值
  • 112. 路径总和 113.路径总和ii
  • 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树

一、找树左下角的值

力扣题目链接 (opens new window)

本题的目标是找到左下角的值,也就是最底层左边的值,可以说用层级遍历更方便一些。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> que;
        int result=0;
        if(root!=NULL) {
            que.push(root);
        };
        
        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;


    }
};

递归法

递归三部曲:

1、确定递归和参数的返回值

参数需要有根节点,还有最大深度,所以不需要返回值返回类型为void。

需要两个全局变量result记录最深节点的值,maxdepth,记录最大深度。

int maxDepth = INT_MIN;   // 全局变量 记录最大深度
int result;       // 全局变量 最大深度最左节点的数值
void traversal(TreeNode* root, int depth)

2、确定终止条件

遇到叶子节点更新最大深度,和result的值

if (root->left == NULL && root->right == NULL) {
    if (depth > maxDepth) {
        maxDepth = depth;           // 更新最大深度
        result = root->val;   // 最大深度最左面的数值
    }
    return;
}

3、单层逻辑

                    // 中
if (root->left) {   // 左
    depth++; // 深度加一
    traversal(root->left, depth);
    depth--; // 回溯,深度减一
}
if (root->right) { // 右
    depth++; // 深度加一
    traversal(root->right, depth);
    depth--; // 回溯,深度减一
}
return;

完整

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){
                depth++;
                traversal(root->left,depth);
                depth--;
            }
            if(root->right){
                depth++;
                traversal(root->right,depth);
                depth--;
            }
            return;
        }

    int findBottomLeftValue(TreeNode* root) {
        traversal(root,0);
        return result;
        

    }
};
控制台

二、路径总和

力扣题目链接 (opens new window)

看这题明显是要回溯和递归。

递归三部曲:

1、确定递归函数的参数和返回类型

需要二叉树的根节点,还需要一个计数器,用于计算和是否为目标和。

遇到了符合条件的路径就需要返回,所以需要有返回值bool

bool traversal(Treenode* cur,int count)

2、确定终止条件

count==0且到了叶子节点

if (!cur->left && !cur->right && count == 0) return true; // 遇到叶子节点,并且计数为0
if (!cur->left && !cur->right) return false; // 遇到叶子节点而没有找到合适的边,直接返回

3、确定单层逻辑

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;

整体

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool traversal(TreeNode* cur,int count){
        if(!cur->left&&!cur->right&&count==0) return true;
        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;
    }


    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root==NULL) return false;
        return traversal(root,targetSum-root->val);
        

    }
};

迭代:

和递归的参数类似,需要存放节点和路径数值总和

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root==NULL) return false;
        stack<pair<TreeNode*,int>> st;

        st.push(pair<TreeNode*,int>(root,root->val));
        while(!st.empty()){
            pair<TreeNode*,int> node =st.top();
            st.pop();
            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;

    }
};

三、路径总和||

力扣题目链接 (opens new window)

依然使用递归算法

递归三部曲:1、确定函数返回值类型和参数

由于要遍历整个树,找到所有符合条件的路径,所以递归函数不需要返回值。

class Solution {
public:
   vector<vector<int>> result;
   vector<int> path;
   void traversal(TreeNode* cur,int count){
       if(!cur->left&&!cur->right&&count==0){
           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;
   }
    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;


    }
};

四、从中序后序遍历序列构造二叉树

力扣题目链接 (opens new window)

思路:以 后序数组的最后一个元素为切割点,先切中序数组,根据中序数组,反过来再切后序数组。一层一层切下去,每次后序数组最后一个元素就是节点元素。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    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;
       }
       vector<int> leftInorder(inorder.begin(),inorder.begin()+delimiterindex);
       vector<int> rightInorder(inorder.begin()+delimiterindex+1,inorder.end());
       postorder.resize(postorder.size()-1);
       vector<int> leftPostorder(postorder.begin(),postorder.begin()+leftInorder.size());
       vector<int> rightPostorder(postorder.begin()+leftInorder.size(),postorder.end());
       root->left=traversal(leftInorder,leftPostorder);
       root->right =traversal(rightInorder,rightPostorder);
       return root;

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

    }
};

感觉挺复杂,没咋看懂。

五、从前序与中序遍历序列构造二叉树

力扣题目链接 (opens new window)

思路和上面一样

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
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());
    }
};

 今天很累,最后两题代码没咋看懂,等明天会再看一遍

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值