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

    The punch line of this one: sum of leaves: pi..pj = root..pj - root..pi.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
        int ret;
        void go(TreeNode *p, int sofar, int tgt, unordered_map<int, unsigned> rec)
        {
            if(!p) return;
            
            sofar += p->val;
            if(sofar == tgt)
            {
                ret ++; // case 1 : from root
            }
            
            int t = sofar - tgt;
            if(rec.find(t) != rec.end())
            {
                ret += rec[t];
            }
            
            rec[sofar] ++;
            go(p->left, sofar, tgt, rec);
            go(p->right,sofar, tgt, rec);
        }
    public:
        int pathSum(TreeNode* root, int sum) 
        {
            ret = 0;
            if(!root) return 0;
            
            go(root, 0, sum, unordered_map<int, unsigned>());
            return ret;
        }
    };
  • 相关阅读:
    实体类实现序列化
    异常处理
    Springboot的模块化使用
    Springboot的开始
    RxJava用法
    okhttp的Post方式
    OKhttp使用
    soundPool声音池
    ScheduledExecutor定时器
    timer定时器
  • 原文地址:https://www.cnblogs.com/tonix/p/6354268.html
Copyright © 2011-2022 走看看