Leetcodeすべてのパス257のバイナリツリー問題解決のアイデアやC ++で実装

免責事項:この記事はブロガーオリジナル記事ですが、許可ブロガーなく再生してはなりません。https://blog.csdn.net/gjh13/article/details/90742767

問題解決のアイデア:

深さ優先探索(DFS)を使用して、深さ優先探索終了条件は次のとおりです。現在のルートノードがリーフノード、すなわち:! Root-ある> &&ルートで左>右真である場合、経路を発見!

/**
 * 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){
        if(!root) return {};
        
        vector<string> res;
        dfs(res, root, to_string(root->val));
        return res;
    }
    void dfs(vector<string>& res, TreeNode* root, string tmp){
        if(!root->left && !root->right){
            res.push_back(tmp);
            return;
        }
        if(root->left)
            dfs(res, root->left, tmp + "->" + to_string(root->left->val));
        if(root->right)
            dfs(res, root->right, tmp + "->" + to_string(root->right->val));
    }
};

 

 

 

おすすめ

転載: blog.csdn.net/gjh13/article/details/90742767