• 【Leetcode】257. Binary Tree Paths


    问题描述:

      就一道简简单单的二叉树搜索 从root到leaf节点的所有路径。竟然敲挫了10发。要哭了。。。

    问题分析:

      深度搜索无疑,应该是受了树遍历思维的局限,一开始把递归返回的条件写成了NULL节点返回,肯定是错的啊 !JInxu同学! 人家都说了是到叶节点了,返回条件肯定是叶子节点啊! 然后判断一下左右子树是否存在进行相应的深搜就好了。

    问题解决:

      DFS。

      int  转 string 有两种方法 ,这里用的sprintf(char[], "%d", int), string = char[]。

      string += char 要注意!int 是0-9还能凑活,如果大于10, int + '0'就是一坨shit。

    代码如下:

      

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
    
        void dfsBinaryTree(TreeNode* root, vector<int> rec, vector<vector<int>>&ret)
        {   
            if(root != NULL && root -> left == NULL && root -> right == NULL){
                if(rec.size()) ret.push_back(rec);
                return ;
            }
            if(root -> left){
                rec.push_back(root -> left -> val);
                dfsBinaryTree(root -> left, rec, ret);
                rec.pop_back();
            }
            if(root -> right){
                rec.push_back(root -> right -> val);
                dfsBinaryTree(root -> right, rec, ret);
                rec.pop_back();
            }
        }
        
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> ret;
            if(root == NULL) return ret;
            vector<int> rec;
            vector<vector<int>> path;
            rec.push_back(root -> val);
            dfsBinaryTree(root, rec, path);
            for(int i = 0; i < path.size(); i ++){
                string tmp = "";
                for(int j = 0; j < path[i].size(); j ++){
                    cout<<"path = "<<path[i][j]<<endl;
                    char t[256];
                    sprintf(t, "%d", path[i][j]);
                    tmp += t;
                    if(j != path[i].size() - 1) tmp += "->";
                }
                ret.push_back(tmp);
            }
            return ret;
        }
    };

    ps: 原来博客会越写越快的 。 makefile 还没学完,耍起题来,不想停,怎么破啊。。哎,,,渣

  • 相关阅读:
    配置 L3 agent
    Why Namespace?
    虚拟 ​router 原理分析
    创建 router 连通 subnet
    用 config drive 配置网络
    cloud
    写在最前面
    使用apktool工具遇到could not decode arsc file的解决办法
    php-fpm优化
    解决官网下载jdk只有5k大小的错误
  • 原文地址:https://www.cnblogs.com/luntai/p/5404506.html
Copyright © 2020-2023  润新知