leetcode-257. 二叉树的所有路径刷题笔记(c++)

写在前面

  • 难度:简单
  • 递归遍历 / 深度优先遍历(dfs)

题目详情

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

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

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

ac代码

  • 解题思想
    • 递归迭代
    • for循环逆序拼装(左右均可能有多个路径)
    • 递归迭代变量、数组值/大小关系!!!
  • 方法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> ans;
        if(!root)
            return ans;
        if(root->left == NULL && root->right == NULL)
            ans.push_back(to_string(root->val));

        vector<string> leftS = binaryTreePaths(root->left);
        for(int i=0; i<leftS.size(); i++)
            ans.push_back(to_string(root->val) + "->" + leftS[i]);

        vector<string> rightS = binaryTreePaths(root->right);
        for(int i=0; i<rightS.size(); i++)
            ans.push_back(to_string(root->val) + "->" + rightS[i]);
        return ans;
    }
};
  • 方法2: 深度优先搜索(Depth-First-Search)
class Solution
{
private:
    vector<string> ans;
public:
    vector<string> binaryTreePaths(TreeNode* root)
    {
        if(!root)
            return ans;
        dfs(root, to_string(root->val));
        return ans;
    }
    void dfs(TreeNode* root, string str)
    {
        // 搜索完一个叶子节点,将数据存入容器
        if (root->left == NULL && root->right == NULL)
        {
            ans.push_back(str);
            return;
        }
        if(root->left != NULL)  // 防止越界取值
            dfs(root->left, str + "->" + to_string(root->left->val));
        if(root->right != NULL)
            dfs(root->right, str + "->" + to_string(root->right->val));
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章