zoukankan      html  css  js  c++  java
  • LeetCode 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"]
    
    Explanation: All root-to-leaf paths are: 1->2->5, 1->3
    
    /**
     * 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 { //树的遍历dfs
    public:
        vector<string> ans;
        void dfs(TreeNode* root, string path){
            if(root){
                path+="->";
                path+=to_string(root->val);
            }else
                return ;
            if(root->left)
                dfs(root->left, path);
            if(root->right)
                dfs(root->right, path);
            if(!root->left&&!root->right)
                ans.push_back(path.substr(2,path.length()-2));
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            string path="";
            dfs(root, path);
            return ans;
        }
    };
    
  • 相关阅读:
    信息量
    MVC4的实战:排球计分(一)(综述)
    排球计分规则3.17
    观后感-----怎样成为一个高手
    本学期最后一个博客
    第五组作业
    个人作业
    第五组作业
    个人作业
    一周的总结
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10058643.html
Copyright © 2011-2022 走看看