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

LeetCode[Tree]: Path Sum II

編輯:C++入門知識

LeetCode[Tree]: 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,

\

return

\

這個題目適合用遞歸來解,我的C++代碼實現如下:

class Solution {
public:
    vector > pathSum(TreeNode *root, int sum) {
        vector > paths;
        vector curr_path;
        if (!root) return paths;

        find(root, sum, paths, curr_path);

        return paths;
    }

private:
    void find(TreeNode *root, int sum, vector > &paths, vector &curr_path) {
        curr_path.push_back(root->val);
        if (root->left == nullptr && root->right == nullptr)
            if (root->val == sum) paths.push_back(curr_path);
        if (root->left) {
            find(root->left, sum - root->val, paths, curr_path);
            curr_path.pop_back();
        }
        if (root->right) {
            find(root->right, sum - root->val, paths, curr_path);
            curr_path.pop_back();
        }
    }
};

時間性能如下圖所示:


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