题目连接
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: vectorbinaryTreePaths(TreeNode* root) { ans.clear(); if (!root) return ans; dfs(root, ""); return ans; }private: vector 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) + "->"); }};