zoukankan      html  css  js  c++  java
  • LeetCode 257 二叉树所有路径

    题目描述链接:https://leetcode-cn.com/problems/binary-tree-paths/

    基本思路:从根节点一直向下深搜即可。当访问到叶子节点时结束。记录一下,可以使用to_string()函数隶属于string头文件,将int转换为string。具体LeetCode代码如下:

    /**
     * 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>res;
        vector<string> binaryTreePaths(TreeNode* root) {
                string path="";
                dfs(root,path);
                return res;
        }
        void dfs(TreeNode* root,string path){
            if(!root){//防止整个树为空或者 非叶子节点只有一个子树的情况
                return;
            }
            if(!root->left&&!root->right){
                path+=to_string(root->val);
                res.push_back(path);
                return ;
            }   
            path+=to_string(root->val);
            path+="->";
    
            dfs(root->left,path);
            dfs(root->right,path);
        }
    };
  • 相关阅读:
    文件上传和下载
    代理模式
    设计模式分类
    单例模式
    抽象工厂模式
    成长
    Java教程
    python面试大全
    python入门教程
    收藏网摘
  • 原文地址:https://www.cnblogs.com/zzw-/p/13295293.html
Copyright © 2011-2022 走看看