桂林北站到阳朔怎么坐车,如何在虚拟机里面做网站,东莞网络安全建设,网页设计与制作课程小结题目链接#xff1a;
力扣#xff08;LeetCode#xff09;官网 - 全球极客挚爱的技术成长平台
我的想法#xff1a; 层次遍历不好解#xff0c;可用找到叶子节点#xff0c;但是他有一个回溯过程#xff0c;他要一直保留路径节点#xff0c;层次迭代不好加回溯。 递归…题目链接
力扣LeetCode官网 - 全球极客挚爱的技术成长平台
我的想法 层次遍历不好解可用找到叶子节点但是他有一个回溯过程他要一直保留路径节点层次迭代不好加回溯。 递归方法
使用回溯三部曲 1.返回值无入参多一个单个叶子节点的路径string和总共路径集合
void tranversal(TreeNode* cur, string path, vectorstring result) 2.停止条件
if (cur-left NULL cur-right NULL) { // 遇到叶子节点string sPath;for (int i 0; i path.size() - 1; i) { // 将path里记录的路径转为string格式sPath to_string(path[i]);sPath -;}sPath to_string(path[path.size() - 1]); // 记录最后一个节点叶子节点result.push_back(sPath); // 收集一个路径return;
} 3.一层循环
if (cur-left) {traversal(cur-left, path, result);// 回溯
}
if (cur-right) {traversal(cur-right, path, result);// 回溯
}
代码
//版本二
class Solution {
private:void traversal(TreeNode* cur, string path, vectorstring result) {path to_string(cur-val); // 中中为什么写在这里因为最后一个节点也要加入到path中if (cur-left NULL cur-right NULL) {result.push_back(path);return;}if (cur-left) {path -;traversal(cur-left, path, result); // 左path.pop_back(); // 回溯 path.pop_back(); // 回溯 -}if (cur-right) {path -;traversal(cur-right, path, result); // 右path.pop_back(); // 回溯path.pop_back(); // 回溯 -}}public:vectorstring binaryTreePaths(TreeNode* root) {vectorstring result;string path;if (root NULL) return result;traversal(root, path, result);return result;}
};