[Easy] 257. Binary Tree Paths

257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Solution

DFS

Runtime: 4 ms, faster than 79.62% of C++ online submissions for Binary Tree Paths.
Memory Usage: 14 MB, less than 5.26% of C++ online submissions for Binary Tree Paths.

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(!root) return res;
        getPath(res, root, to_string(root->val));
        return res;
    }
private:
    void getPath(vector<string>& s, TreeNode* root, string t){
        if(!root->left && !root->right){
            s.push_back(t);
            return;
        }
        if(root->left) getPath(s, root->left, t+"->"+to_string(root->left->val));
        if(root->right) getPath(s, root->right, t+"->"+to_string(root->right->val));
    }
};
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读