zoukankan      html  css  js  c++  java
  • 437. Path Sum III

    原题:

    437. Path Sum III

    解题:

    思路1就是:以根节点开始遍历找到适合路径,以根节点的左孩子节点开始遍历,然后以根节点的右孩子节点开始遍历,不断循环,也就是以每个节点为起始遍历点

    代码如下:

    class Solution {
    public:
        int pathSum(TreeNode* root, int sum) 
    	{
            if(!root) return 0;
    		int count = getPath(root,0,sum) + pathSum(root->left,sum) + pathSum(root->right,sum);
    		return count;
        }
    	int getPath(TreeNode* node, int target, int sum)
    	{
    		if(!node) return 0;
    		target += node->val;
    		return (target == sum) + getPath(node->left, target, sum) + getPath(node->right, target, sum);
    	}
    };
    

     以下代码是论坛里看到的,思路差不多,也是递归:

    class Solution {
    public:
        int pathSum(TreeNode* root, int sum) {
           path(root,0,sum);
            return total;
        }
        int total;
        void incrementTotal(){
            this->total++;
            
        }
        
        void path(TreeNode* root,int sum, int target){
            if(root != NULL){
              
                checkpath(root,0,target);
                path(root->left,0,target);
                path(root->right,0,target);
            }
        }
        void checkpath(TreeNode* root,int sum,int target){
         
            if(root == NULL){
                return;
            }
            int check = sum + root->val;
            if(check == target){
                incrementTotal();
            }
                checkpath(root->left,check,target);
                checkpath(root->right,check,target);
              
        }
              
    };
    

      

  • 相关阅读:
    Linux 性能优化--理解 CPU 使用率和平均负载
    sqlalchemy ORM
    redis缓存数据库
    基于CentOS安装FTP服务器
    python3之platform模块
    paramiko模块
    shelve模块
    Vue入门---属性、style和class绑定方法
    Vue入门---事件与方法详解
    Vue入门---常用指令详解
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8530299.html
Copyright © 2011-2022 走看看