zoukankan      html  css  js  c++  java
  • leetcode刷题笔记 257题 二叉树的所有路径

    leetcode刷题笔记 257题 二叉树的所有路径

    源地址:257. 二叉树的所有路径

    问题描述:

    给定一个二叉树,返回所有从根节点到叶子节点的路径。

    说明: 叶子节点是指没有子节点的节点。

    示例:

    输入:

    1
    /
    2 3

    5

    输出: ["1->2->5", "1->3"]

    解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

    /*
    基于DFS思想,遍历过程中记录路径,遇到叶子节点,将路径加入res列表中
    */
    /**
     * Definition for a binary tree node.
     * class TreeNode(var _value: Int) {
     *   var value: Int = _value
     *   var left: TreeNode = null
     *   var right: TreeNode = null
     * }
     */
    import scala.collection.mutable
    object Solution {
        def binaryTreePaths(root: TreeNode): List[String] = {
            val res = mutable.ListBuffer[String]()
            val path = mutable.ListBuffer[Int]()
    
            if (root != null) dfs(root)
            return res.toList
    
            def dfs(root: TreeNode): Unit = {
                path.append(root.value)
                if (root.left == null && root.right == null){
                    val str = path.toList.mkString("->")
                    res.append(str)
                } else {
                    if (root.left != null) dfs(root.left)
                    if (root.right != null) dfs(root.right)
                }
                path.remove(path.length-1)
            }
            return res.toList
        }
    }
    
  • 相关阅读:
    邮件发送工具类
    redis在项目中配置
    搭建zookeeper集群
    activeMQ安装
    solr安装配置中文分词IK
    reids安装
    jdk/tomcat/mysql在linux下安装
    使用poi进行excel导入
    linux 大杂烩
    找包网址
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13905438.html
Copyright © 2011-2022 走看看