天天看點

LeetCode:Binary Tree Paths

Binary Tree Paths

Total Accepted: 51384  Total Submissions: 175285  Difficulty: Easy

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

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags   Tree Depth-first Search Hide Similar Problems   (M) Path Sum II

思路:

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> paths;
        
        string path = "";
        if(root) binaryTreePaths(root, path, paths);
        
        return paths;
    }
    
    // 自定義函數  DFS
    void binaryTreePaths(TreeNode* root, string path, vector<string>& paths) {
        
        if(!(root->left) && !(root->right)) paths.push_back(path + to_string(root->val));
        if(root->left)
            binaryTreePaths(root->left, path + to_string(root->val) + "->", paths);
        if(root->right)
            binaryTreePaths(root->right, path + to_string(root->val) + "->", paths);
        
    }
};