LeetCode 257. Binary Tree Paths
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 257. Binary Tree Paths相关的知识,希望对你有一定的参考价值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<string> binaryTreePaths(TreeNode* root) { 13 vector<string> res; 14 if(!root) return res; 15 help(root,res,""); 16 return res; 17 18 } 19 20 void help(TreeNode* root, vector<string>& res, string cur){ 21 if(!root) return; 22 stringstream ss; 23 ss<<root->val; 24 string tmp; 25 ss>>tmp; 26 if(cur != "") cur = cur + "->" + tmp; 27 else cur = tmp; 28 if(!root->left && !root->right){ 29 res.push_back(cur); 30 return; 31 } 32 help(root->left,res,cur); 33 help(root->right,res,cur); 34 35 } 36 };
注意应该判断cur是否为空。否则结果会是 "->1->2".
以上是关于LeetCode 257. Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 257. Binary Tree Paths
Java [Leetcode 257]Binary Tree Paths
leetcode?python 257. Binary Tree Paths
leetcode 257. Binary Tree Paths