leetcode Binary Tree Paths

来源:互联网 发布:vip视频盒子app源码 编辑:程序博客网 时间:2024/06/05 23:42

原题链接:https://leetcode.com/problems/binary-tree-paths/

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"]

/** * 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) {        ans.clear();        if (!root) return ans;        dfs(root, "");        return ans;    }private:    vector<string> ans;    void dfs(TreeNode *x, string ret) {        if (!x) return;        if (!x->left && !x->right) {            ans.push_back(ret + to_string(x->val));            return;        }        dfs(x->left, ret + to_string(x->val) + "->");        dfs(x->right, ret + to_string(x->val) + "->");    }};
0 0
原创粉丝点击