程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [leetcode]Path Sum II

[leetcode]Path Sum II

編輯:C++入門知識

[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]
]

分析:
這道題目算是Path Sum的延伸,只不過要求出所有從根到樹葉的路徑上節點和為給定值的路徑,並放到一個vector中返回。采取類似於Path Sum遞歸思路,每次遞歸都會建立一個新的vector,復制之前的vector內容,並將當前節點的值放入,如果當前節點是葉節點,並且路徑上節點和滿足要求,就將新的vector放入最終返回的vector中。
代碼:

class Solution {
public:
    vector> res;
    vector> pathSum(TreeNode* root, int sum) {
         if(!root)
            return res;
        vector tmp;
        pathSum1(root,sum,tmp);
         return res;
    }
    void pathSum1(TreeNode* root, int sum,vector tmp)
    {
         if(!root)
            return ;
        vector tmp1;
        tmp1 = tmp;
        tmp1.push_back(root->val);
        if(!root->left&&!root->right)
        {
            if(root->val==sum)
               res.push_back(tmp1);
            return;
        }
        pathSum1(root->left,sum-root->val,tmp1);pathSum1(root->right,sum-root->val,tmp1);
    }
};

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved