Leetcode-257. Binary Tree Paths

来源:互联网 发布:青少年行知实践园的题 编辑:程序博客网 时间:2024/06/05 02:03

Description:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]
解题思路:
本题利用深度遍历解决,每次访问到叶子结点,开始打印路径。这里需要注意的是,每次递归返回后需要删除当前的叶子结点,防止路径重复打印。

Solution:
class Solution {
public: 
    
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result; //保存所有的路径信息
        if(!root)   return result;
        string  temp = to_string(root->val); //以字符串形式保存当前访问到的结点信息
        DFS(root, result, temp);
        return result;
    }
    void DFS(TreeNode* root, vector<string>& result, string temp)// 深度遍历
    {
        int index;
        if(!root->left&&!root->right)   //访问到叶子结点,表示一条完整的路径,存入vector
        {  
            result.push_back(temp);
            return;
        }
        if(root->left)   //递归左子树
        {
            temp += "->" + to_string(root->left->val);
            DFS(root->left, result, temp);
            index = temp.rfind("->", temp.size()-1);//递归返回需要删除当前结点信息
            temp.erase(index, temp.size() - index);
            
        }
        if(root->right) //递归右子树
        {
            temp += "->" + to_string(root->right->val);
            DFS(root->right, result, temp);
            index = temp.rfind("->", temp.size()-1);
            temp.erase(index, temp.size() - index);
        }
    }
 
};

原创粉丝点击