您的位置:首页 > 其它

leetcode 每日一题 257. Binary Tree Paths

2016-03-29 12:47 357 查看
给出二叉树,求所有从根到叶子节点的路径并打印

这道题可以用递归解(DFS),但是对递归理解的还是不够,并且判断条件的时候太大意了 一直RE,烦得很

后来经臭臭指点找到了原因。

vector<string> binaryTreePaths(TreeNode* root) {
TreeNode* head=root;  //记得赋值啊!
vector<string> res;
string str="";
//if(head==NULL) return res;
printPath(head,res,str);
return res;
}

void printPath(TreeNode* head,vector<string> &res,string str){
if(head==NULL) return;    //停止条件
str+=to_string(head->val);
if(head->left==NULL&&head->right==NULL){
res.push_back(str);
return;    //停止条件,也就是停止到上一个递归
}
else{
str+="->";
printPath(head->left,res,str);   //分开考虑则不需要判断head
printPath(head->right,res,str);
}
}


在上面的程序中,由于else中没有判断左右孩子是否为空的情况,因此需要加一个head==NULL作为终止条件,这个是不能加到主函数的

但如果判断了,则可以在主函数中判断root

代码如下 https://leetcode.com/discuss/93742/c-non-recursive-version-and-recursive-version
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root == NULL) return res;
dfs(root, to_string(root->val), res);
return res;
}

void dfs(TreeNode* root, string path, vector<string>& res) {
if (root->left == NULL && root->right == NULL) {
res.push_back(path);
}

if (root->left != NULL)
dfs(root->left, path + "->" + to_string(root->left->val), res);

if (root->right != NULL)
dfs(root->right, path + "->" + to_string(root->right->val), res);
}


另外就是to_string函数的使用,之前没怎么接触过~

此题过段时间应再刷一遍····很多很多需要避免的漏洞
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: