Leetcode 257. 二叉树的所有路径

地址 https://leetcode-cn.com/problems/binary-tree-paths/

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

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

示例:

输入:

   1
 /   \
2     3
 \
  5

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

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

解答 

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> vv;
    
    void dfs(TreeNode* root,string s){
        if(root == NULL){
            return;
        }
        
        s+=to_string(root->val);
        
        if(root->right == NULL && root->left == NULL){
            vv.push_back(s);
            return;
        }
        s += "->";
        dfs(root->left,s);
        dfs(root->right,s);
        
    }
    
    vector<string> binaryTreePaths(TreeNode* root) {
        string s;
        dfs(root,s);
        
        return vv;
    }
};

 

posted on 2020-05-09 12:28  itdef  阅读(219)  评论(0)    收藏  举报

导航