[2]基础数据结构,二叉树的遍历

二叉树的遍历

题目链接:
https://leetcode-cn.com/problems/binary-tree-paths/
部分参考于:
https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode-solution/

算法

深度优先搜索DFS。
有人用BFS就是完全为了用而用的吧,我觉得逻辑关系来看的话,其实应该是用深度优先搜索更好。

函数

string to_string(int val)
将val转化为string,重载之后可以将各种稀奇古怪都转化成string。就是感觉C++好用就在这里。可能Python更更好用就在emmmm。

代码实现

/**
 * 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 construct_paths(TreeNode * root,string path,vector<string>& paths){
    
    
        if (root != nullptr) {
    
    
            path += to_string(root->val);
            if (root->left == nullptr && root->right == nullptr) {
    
    
                paths.push_back(path);//是叶子节点放入路径之中,此路径完结                              
            } else {
    
    
                path += "->";//不是叶子节点则为了满足格式微调,继续遍历
                construct_paths(root->left, path, paths);//左遍历
                construct_paths(root->right, path, paths);//右遍历
            }
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
    
    
        vector<string> paths;
        construct_paths(root,"",paths);
        return paths;
    }
};


细节特别标注一下:
函数参数最后的paths,应该用vector< string >&,否则将会出现返回值为空[]类似的情况。毕竟是没有用指针,如果再不用引用的话,就相当于按值传递参数了。这个函数就失去了意义,按值传递,结果返回值为void。
小小传值,可笑可笑。

(明天开始爆肝JavaScript (嘶嘶嘶

猜你喜欢

转载自blog.csdn.net/weixin_47741017/article/details/108413405