美文网首页
257. Binary Tree Paths

257. Binary Tree Paths

作者: SilentDawn | 来源:发表于2018-09-18 08:55 被阅读0次

    Problem

    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"]
    
    Explanation: All root-to-leaf paths are: 1->2->5, 1->3
    

    Code

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    static int var = [](){
        std::ios::sync_with_stdio(false);
        cin.tie(NULL);
        return 0;
    }();
    class Solution {
    private:
        vector<string> res;
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            if(root==NULL)
                return res;
            translate("",root);
            return res;
        }
        void translate(string path,TreeNode* node){
            if(node->left==NULL && node->right==NULL){
                res.push_back(path+to_string(node->val));
            }
            else{
                if(node->left)
                    translate(path+to_string(node->val)+"->",node->left);
                if(node->right)
                    translate(path+to_string(node->val)+"->",node->right);
            }
        }
    };
    

    Result

    257. Binary Tree Paths.png

    相关文章

      网友评论

          本文标题:257. Binary Tree Paths

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