题目链接:https://leetcode.com/PRoblems/binary-tree-paths/?tab=Description
题目描述:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / /2 3 / 5All root-to-leaf paths are:
["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> binaryTreePaths(TreeNode* root) { vector<string> result; string tmpPath=""; DFS(root,tmpPath,result); return result; } void DFS(TreeNode* root,string path,vector<string> &Paths) { if(root==NULL) return; if(root->left==NULL&&root->right==NULL) { path+=to_string(root->val); Paths.push_back(path); return; } path+=to_string(root->val); path+="->"; DFS(root->left,path,Paths); DFS(root->right,path,Paths); }};
新闻热点
疑难解答