zoukankan      html  css  js  c++  java
  • leetcode 257. Binary Tree Paths

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

    题目大意:
    输出二叉树的所有路径
    思路:
    先序遍历,记录路径。为了回溯,临时存储路径的数据结构得具有弹出最后一个元素的功能,我的代码里面用的是vector

    /**
     * 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> v;
        void dfs(TreeNode* root, vector<string> s) {
            if (root == nullptr) return;
            if ((root->left == nullptr) && (root->right == nullptr)) {
                if(s.size() == 0) s.push_back(to_string(root->val));
                else s.push_back("->" + to_string(root->val));
                string t = "";
                for (int i = 0; i < s.size(); ++i) {
                    t += s[i];
                }
                v.push_back(t);
                return ;
            }
            if(s.size() == 0) s.push_back(to_string(root->val));
            else s.push_back("->" + to_string(root->val));
            dfs(root->left, s);
            dfs(root->right, s);
            s.pop_back();
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> s;
            dfs(root, s);
            return v;
        }
    };
    
  • 相关阅读:
    mysql自增长字段设置
    查看docker的挂载目录
    centos rpm安装jdk1.8
    mybatis-地区三表生成地区树
    post表单、json接口
    git子模块使用
    解决Windows系统80端口被占用
    交换机基础命令
    JMX协议
    WMI协议
  • 原文地址:https://www.cnblogs.com/pk28/p/7648315.html
Copyright © 2011-2022 走看看