PRoblem:Given a binary tree, return all root-to-leaf paths.
Solution:每個(gè)結(jié)點(diǎn)記錄從root至其的path,當(dāng)結(jié)點(diǎn)無(wú)左右孩子時(shí),將path傳入進(jìn)vector。
這里需要注意的是,recordPath函數(shù)中,path記錄著root至結(jié)點(diǎn)的path,不可改變,不能加&(reference),而pathResult需要添加新的path,所以要加&。
void recordPath(TreeNode* tn,vector<int> path,vector< vector<int> >& pathResult)class Solution { void recordPath(TreeNode* tn,vector<int> path,vector< vector<int> >& pathResult){ path.push_back(tn->val); if(!tn->left&&!tn->right) pathResult.push_back(path); if(tn->left) recordPath(tn->left,path,pathResult); if(tn->right) recordPath(tn->right,path,pathResult); return; } void convert(ve,vector< vector<int> > path)ctor<string>& result{int rowSize=path.size(); for(int i=0;i<rowSize;i++){ string tmp; tmp=to_string(path[i][0]); for(int j=1;j<path[i].size();j++){ tmp+="->"; tmp+=to_string(path[i][j]); } result.push_back(tmp); } return; }public: /** * @param root the root of the binary tree * @return all root-to-leaf paths */ vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; vector< vector<int> > pathResult; vector<int> tmp; if(!root) return result; recordPath(root,tmp,pathResult); convert(result,pathResult); return result; }};
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注