1. 程式人生 > >牛客網刷題|二叉樹中和為某一值的路徑

牛客網刷題|二叉樹中和為某一值的路徑

題目來源:牛客網

程式設計連線

題目描述

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

解析:

經典DFS演算法,深度優先演算法

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>>ret;
        vector<int
>
path; dfs(ret,root,path,expectNumber,0,0); return ret; } void dfs(vector<vector<int>>&ret,TreeNode* root,vector<int>&path,int expectNumber,int len,int sum) { if(root == nullptr) return; if(len == path.size()) path.push_back(root->val); else
path[len] = root->val; if(sum + root->val == expectNumber && root->left == nullptr && root->right == nullptr) { vector<int>arr(len+1); for(int i=0;i<len+1;i++) { arr[i] = path[i]; } ret.push_back(arr); } dfs(ret,root->left,path,expectNumber,len+1
,sum + root->val); dfs(ret,root->right,path,expectNumber,len+1,sum + root->val); } };