当前位置:   article > 正文

leetcode257.二叉树的所有路径

leetcode257.二叉树的所有路径

解法1:DFS

这题的思路是使用前序遍历,然后记住string参数这里只能值传递,不能引用传递,只有使用值传递才能保证每个调用栈才能使用不同的string副本!

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> v;
        string s;
        dfs(root,v,s);
        return v;
    }
    
    void dfs(TreeNode* node,vector<string>& v,string s){
        if(node){
            s.append(to_string(node->val));
            if(!node->left&&!node->right){
                v.push_back(s);
                
            }else{
                s.append("->");
                dfs(node->left,v,s);
                dfs(node->right,v,s);
            }
        }
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

解法2:BFS

手写一算就懂了!

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> v;
        queue<TreeNode*> node_q;
        queue<string> path_q;
        bfs(v,root,node_q,path_q);
        return v;
    }
    void bfs(vector<string>& v,TreeNode* root,queue<TreeNode*>& node_q,queue<string>& path_q){
        node_q.push(root);
        path_q.push(to_string(root->val));
        while(!node_q.empty()){
            TreeNode* node=node_q.front();
            string path = path_q.front();
            node_q.pop();
            path_q.pop();
            if(!node->left&&!node->right){
                v.push_back(path);
            }else{
                if(node->left){
                    node_q.push(node->left);
                    path_q.push(path+"->"+to_string(node->left->val));
                }
                if(node->right){
                    node_q.push(node->right);
                    path_q.push(path+"->"+to_string(node->right->val));
                }
            }
        }
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/243745
推荐阅读
相关标签
  

闽ICP备14008679号