zoukankan      html  css  js  c++  java
  • LC112 路径总和

    终于自己做出来一道。。。

    递归思路1

    参考递归求解最大深度,构造新函数,将节点当前路径和当作额外参数传入
    这个题比较特殊的地方在于,必须是叶子节点所在的路径才有效,因此在return true的条件中加入了left right均为`nullptr
    返回时使用||不影响某个分支上的正确结果

    class Solution {
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            return depth(root, 0, sum);
        }
        bool depth(TreeNode* root, int res, int sum){
            if(root == nullptr)
                return false;
            //这两行注释也可以通过,不知道为什么,其实少了返回条件,猜测是因为函数没有返回值,而bool默认值为false
            //if(res + root->val == sum && root->left == nullptr && root->right == nullptr)
                //return true;  
            if(root->left == nullptr && root->right == nullptr)
                return (res + root->val) == sum;  
            bool lres = depth(root->left, res + root->val, sum);
            bool rres = depth(root->right, res + root->val, sum);
            return lres || rres;
        }
    };
    

    递归思路2

    官方题解中采用的方法很巧妙,通过剩余值来代替上述方法中的路径和,直接在函数中递归即可

    class Solution {
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            if(root == nullptr)
                return false;
            if(root->left == nullptr && root->right == nullptr)
                return sum == root->val;
            return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
        }
    };
    

    非递归思路 广度优先搜索

    使用两个队列,分别存储节点以及当前节点路径和,节点的子节点入队列时,当前节点的路径和与子节点的值和相加入队列

    class Solution {
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            if(root == nullptr)
                return false;
            queue<TreeNode*> nodes;
            queue<int> sums;
            nodes.push(root);
            sums.push(root->val);
            while(!nodes.empty()){
                TreeNode* nowNode = nodes.front();
                int nowSum = sums.front();
                if(nowNode->left == nullptr && nowNode->right == nullptr && nowSum == sum)
                    return true;
                if(nowNode->left != nullptr){
                    nodes.push(nowNode->left);
                    sums.push(nowSum + nowNode->left->val);
                }
                if(nowNode->right != nullptr){
                    nodes.push(nowNode->right);
                    sums.push(nowSum + nowNode->right->val);
                }
                nodes.pop();
                sums.pop();
            }
            return false;
        }
    };
    
  • 相关阅读:
    关于工作流程引擎中的岗位的设置的问题
    将要发布的开源CCOA的照片一览
    关于多个checkbox在IE6下自由表单设计器中的兼容问题
    ccflow流程自动发起功能增加,如何按指定的时间触发方式发起流程?
    Windows 如何远程强行关机
    Report bulder
    微软sample and code down web address
    如何查看sql server的死锁情况
    如何读取数据的所有用户表
    复制和数据库镜像
  • 原文地址:https://www.cnblogs.com/imagineincredible/p/13323933.html
Copyright © 2011-2022 走看看