本次的題目要求尋找樹根到葉子的所有路徑,並以string的方式輸出。基本思想上我所採用深度優先搜索算法(DP)解決樹的問題。
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"]首先給出對樹節點的結構:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
先給出主要搜索函數,創建存儲每一條路徑的vector path,初始先判斷根否為NULL,如果為空的話則返回當前path,我創建輔助搜索路徑的函數方便構想,其中利用DP算法實現。用to_string函數是為了將int類型轉換成string。
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> path;
if(!root)
return path;
dp(path, root, to_string(root->val));
return path;
}
在輔助搜索路徑的函數中,先判斷當前的樹節點有沒有左或右的孩子,如果都有則將當前節點以及之前紀錄的節點加入path的路徑紀錄中並返回。
如果否,則分別利用左右孩子繼續調用dp函數,直到判斷到中止。每次調用的時候都將入當前路徑已集結點的字符串,在終止處才將其存入path中。
void dp(vector<string>& path, TreeNode* root, string t) {
if(!root->left && !root->right) {
path.push_back(t);
return;
}
if(root->left)
dp(path, root->left, t + "->" + to_string(root->left->val));
if(root->right)
dp(path, root->right, t + "->" + to_string(root->right->val));
}