LeetCode257. Binary Tree Paths

2016-11-17  本文已影响0人  Yuu_CX

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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读