leetcode257。バイナリツリー/ bfs、dfsのすべてのパス

件名:257.二分木のすべてのパス

バイナリツリーを指定すると、ルートノードからリーフノードへのすべてのパスを返します。

説明:葉ノードは、子ノードのないノードを指します。

例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

出典:LeetCode
リンク:https ://leetcode-cn.com/problems/binary-tree-paths
著作権はLeetCode が所有しています商用転載については、正式な許可書にご連絡ください。非商用転載については、出典を明記してください。

基本的な考え方:DFS

/**
 * 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:
    vector<string> res;
    vector<string> binaryTreePaths(TreeNode* root) {
    
    
        if(root == NULL)
            return res;        
        dfs(root, "");
        return res;
    }
    void dfs(TreeNode * root, string cur){
    
    
        string temp = to_string(root->val);
        if(cur == ""){
    
                
            cur += temp;
        }
        else{
    
    
            cur += "->" + temp;
        }

        if(root->left == NULL && root->right == NULL){
    
    //遇到根节点存放结果
            res.push_back(cur);
            return;
        }
        if(root->left){
    
    
            dfs(root->left, cur);
        }
        if(root->right){
    
    
            dfs(root->right, cur);
        }
        

    }
};

基本的な考え方2:bfs

bfsを使用することもできます

  • 2つのキューを維持します。1つのキューは現在のノードを格納するために使用され、1つのキューはノードによって形成されるパスを格納するために使用されます。
  • ノードがキューから排出されるたびに、パスも同時に排出されます。
  • 現在のノードに左の子がある場合、左の子は現在のパスに接続され、パスがエンキューされます。同様に、現在のノードに子がある場合、現在のノードの右の子も現在のパスに追加され、パスがエンキューされます。
/**
 * 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:
    vector<string> binaryTreePaths(TreeNode* root) {
    
    
        vector<string> res;
        if(root == NULL)
            return res;
        queue<TreeNode*> q;
        queue<string> path;
        q.push(root);
        path.push(to_string(root->val));
        while(!q.empty()){
    
    
            auto temp_n = q.front();
            auto temp_p = path.front();
            q.pop();
            path.pop();
            if(temp_n->left == NULL && temp_n->right == NULL){
    
    
                res.push_back(temp_p);
            }
            if(temp_n->left){
    
    
                q.push(temp_n->left);
                path.push(temp_p + "->" + to_string(temp_n->left->val));
            }
            if(temp_n->right){
    
    
                q.push(temp_n->right);
                path.push(temp_p + "->" + to_string(temp_n->right->val));
            }
        }
        return res;
    }
};

おすすめ

転載: blog.csdn.net/qq_31672701/article/details/108407721