leetcode 每日一题 257. Binary Tree Paths


给出二叉树,求所有从根到叶子节点的路径并打印


这道题可以用递归解(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函数的使用,之前没怎么接触过~

此题过段时间应再刷一遍····很多很多需要避免的漏洞

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值