zoukankan      html  css  js  c++  java
  • 树上的BFS与DFS

    树上的BFS与DFS

    bfs与之前学习的没有什么不同,主要就是对树的层序遍历

    dfs是比较抽象的,一般比较难想而且时间复杂度相对于bfs来说会更高。

    例题:

    1. 二叉树的锯齿形层序遍历

    https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/

    思路:用双端队列来维护入队和出队的节点。

    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            vector<vector<int>> ans;
            if(root == nullptr) return ans;
            deque<TreeNode*>q;
            q.push_back(root);
            int flag = 0;
            while(!q.empty()){
                int n = q.size();
                vector<int>tmp;
                for(int i=0;i<n;i++){    
                    if(flag & 1){
                        TreeNode* p = q.back();
                        q.pop_back();
                        tmp.push_back(p->val);
                        if(p->right != nullptr) q.push_front(p->right);
                        if(p->left != nullptr) q.push_front(p->left);
                    }
                    else{
                        TreeNode* p = q.front();
                        q.pop_front();
                        tmp.push_back(p->val);
                        if(p->left != nullptr) q.push_back(p->left);
                        if(p->right != nullptr) q.push_back(p->right); 
                    }
                }
                flag++;
                ans.push_back(tmp);
            }
            return ans;   
        }
    };
    
    

    2.目标和

    https://leetcode-cn.com/problems/target-sum/

    给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。

    返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

    思路:dfs找到可行解

    class Solution {
    public:
        int findTargetSumWays(vector<int>& nums, int S) {
            return findTarget(nums, 0, (long)S);
        }
    
        long findTarget(vector<int> &nums, int index, long target) {
            if(index == nums.size()) {
                return target == 0 ? 1 : 0;
            }
    
            return findTarget(nums, index+1, target + nums[index])
            + findTarget(nums, index+1, target - nums[index]);
        }
    };
    
    
    七月在野,八月在宇,九月在户,十月蟋蟀入我床下
  • 相关阅读:
    Simple Form Fading
    CResizableFormView
    User-Defined Multi-Lingual Applications
    Automatic Resizing of a FormView Based Application When the User Toggles the Control Bars On or Off
    Save Zip File in Access Database With File Encryption in C#
    continue
    break
    declare/typeset
    bg/fg/jobs
    .
  • 原文地址:https://www.cnblogs.com/voids5/p/14381387.html
Copyright © 2011-2022 走看看