• 257. Binary Tree Paths


    package LeetCode_257
    
    /**
     * 257. Binary Tree Paths
     * https://leetcode.com/problems/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
     * */
    class TreeNode(var `val`:Int){
        var left:TreeNode?=null
        var right:TreeNode?=null
    }
    class Solution {
        /*
        * solution: recursion, Time complexity:O(n), Space complexity:O(n)
        * */
        private val list = ArrayList<String>()
    
        fun binaryTreePaths(root: TreeNode?): List<String> {
            val path = ""
            return list
        }
    
        private fun help(root: TreeNode?, list:ArrayList<String>, path_: String){
            if (root==null){
                return
            }
            val path = "$path_->${root.`val`}"
            if (root.left == null && root.right == null){
                //is leaf,add path without "->" in head of path
                //for example: path:->1->2->5, just insert 1->2->5 into list
                list.add(path.substring(2))
                return
            }
            if (root.left!=null){
                help(root.left, list, path)
            }
            if (root.right!=null){
                help(root.right, list, path)
            }
        }
    }
  • 相关阅读:
    Spring自定义注解简单使用四步走
    关于Mybaits映射一点心得
    设置UIButton文字大小颜色不同
    AFNetworking上传文件
    解决UITableView头部空白
    iOS获取文件和文件夹大小
    编译ffmpeg(iOS)
    让MySql支持Emoji表情
    MySQL重置密码(OSX)
    iOS多线程总结
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13851686.html
Copyright © 2020-2023  润新知