zoukankan      html  css  js  c++  java
  • Path Sum II

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    

    return

    [
       [5,4,11,2],
       [5,8,4,5]
    ]


    万万没想到啊,竟然有负数,所以剪枝条件算是错了。而且用了个全局变量,写的烂透了……

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int> > re; 
        vector<vector<int> > pathSum(TreeNode *root, int sum) {
            if( root == NULL)return re;
            vector<int> vec;
            path(root,sum,vec);
            return re;
            
        }
        
        void path(TreeNode *root, int left , vector<int> vec)
        {
            if(root == NULL)return;
            if(root->left == NULL && root->right == NULL)
            {
                if(left == root->val)
                {
                    vec.push_back(root->val);
                    re.push_back(vec);
                }
            }
            else
            {
                //if(left <= root->val)return;
                //else
                {
                    vec.push_back(root->val);
                    left -= root->val;
                    path(root->left,left,vec);
                    path(root->right,left,vec);
                }
            }
        }
    };
  • 相关阅读:
    颓废ing
    Linux下PF_PACKET的使用(todo)
    TIPC协议(todo)
    TOP命令详解(todo)
    so查找顺序
    把lib打包到so中
    -Bsymbolic: 优先使用本地符号
    GitHub 上最火的 Python 开源项目zz
    __attribute__((weak)) zz
    kmalloc(zz)
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3578599.html
Copyright © 2011-2022 走看看