Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / / 2 3 / 5 All root-to-leaf paths are:
[“1->2->5”, “1->3”]
深搜,簡單的遞歸: 和之前不一樣的是,搜索到葉子結點就需要返回,同時要在葉子結點處將本次的路徑保存進結果的vector。 之所以又寫了一個dfs是為了可以在遞歸的過程中同時記錄下路徑。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> rlt; dfs(root, "", rlt); return rlt; } void dfs(TreeNode* root, string sPRe, vector<string> &res) { if (!root) return; spre += to_string(root->val); if (!root->left && !root->right) { res.push_back(spre); return ; } spre += "->"; if(root->left && root->right) { dfs(root->left,spre,res); dfs(root->right,spre,res); } else if(!root->left) { dfs(root->right,spre,res); } else if(!root->right) { dfs(root->left,spre,res); } return ; }};新聞熱點
疑難解答