zoukankan      html  css  js  c++  java
  • [LeetCode] 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]
    ]
    
    Hide Tags
     Tree Depth-first Search
     

    思路:dfs,递归,注意标红的语句

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
        vector<vector<int> > m_res;
        vector<int>  m_vec;
        public:
            void dfs(TreeNode * root, int sum)
            {
                if(root == NULL)
                    return;
                if(root->left == NULL && root->right == NULL)
                {   
                    if(root->val == sum)
                    {   
                        m_vec.push_back(root->val);
                        m_res.push_back(m_vec);
                        m_vec.pop_back();
                    }   
                    return;
                }   
    
                m_vec.push_back(root->val);
                if(root->left)
                {   
                    dfs(root->left, sum-root->val);
                }   
                if(root->right)
                {
                    dfs(root->right, sum-root->val);
                }
                m_vec.pop_back();
            }
    
            vector<vector<int> > pathSum(TreeNode *root, int sum)
            {
                m_vec.clear();
                m_res.clear();
    
                dfs(root, sum);
                return m_res;
            }
    };
  • 相关阅读:
    python day05
    python day04
    python day03
    python day02
    计算机基本了解
    流程控制
    MFC程序中创建文件夹(文件路径)
    svn移动目录并且保存历史日志
    C++单例模式的问题
    PtInRect 的详细范围
  • 原文地址:https://www.cnblogs.com/diegodu/p/4414446.html
Copyright © 2011-2022 走看看