美文网首页
LeetCode257. Binary Tree Paths

LeetCode257. Binary Tree Paths

作者: Yuu_CX | 来源:发表于2016-11-17 09:04 被阅读0次

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

class Solution {
public:
    vector<string> v;
    void dfs(TreeNode* root,string temp){
        if(root->left==NULL&&root->right==NULL){ 
            v.push_back(temp);
            return;
        }
        if(root->left){
            dfs(root->left,temp+"->"+to_string(root->left->val));
        }
        if(root->right){
            dfs(root->right,temp+"->"+to_string(root->right->val));
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        if(root==NULL) return v;
        dfs(root,to_string(root->val));
        return v;
    }
};

相关文章

网友评论

      本文标题:LeetCode257. Binary Tree Paths

      本文链接:https://www.haomeiwen.com/subject/owkdpttx.html