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);
              
        }
              
    };
    

      

  • 相关阅读:
    ITMS-90809
    iOS ipa 优化减小安装大小
    Xcode 常用路径
    如何查看 Assets.car 内资源
    UILabel 实现圆角
    iOS 改变 UITextField 的 Placeholder 的字体与颜色
    ATS (App Transport Security)
    iOS semaphore 使用
    macOS 自定义 NSButton
    iOS开发——设计模式那点事
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8530299.html
Copyright © 2011-2022 走看看