• LeetCode–二叉树的所有路径


    LeetCode–二叉树的所有路径

    博客说明

    文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

    介绍

    257. 二叉树的所有路径

    题目

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

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

    示例:
    输入:
    
       1
     /   
    2     3
     
      5
    
    输出: ["1->2->5", "1->3"]
    
    解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
    

    思路

    深度优先遍历 DFS

    代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> paths = new ArrayList<String>();
            dfs(root,"",paths);
            return paths;
        }
    
        public void dfs(TreeNode root,String path,List<String> paths){
            if(root != null){
                StringBuffer pathSB = new StringBuffer(path);
                pathSB.append(Integer.toString(root.val));
                if(root.left == null && root.right == null){
                    paths.add(pathSB.toString());
                }else{
                    pathSB.append("->");
                    dfs(root.left,pathSB.toString(),paths);
                    dfs(root.right,pathSB.toString(),paths);
                }
            }
        }
    }
    

    感谢

    Leetcode

    以及勤劳的自己,个人博客GitHub

    微信公众号

  • 相关阅读:
    玩转树莓派《二》——用python实现动画与多媒体
    pygame(一)
    玩转树莓派(一)
    pythonchallenge(七)
    springmvc定时器
    maven打包成第三方jar包且把pom依赖包打入进来
    mybatis之动态SQL
    黑马12期day01之html&css
    千万级数据表删除特定字断
    自动跳转
  • 原文地址:https://www.cnblogs.com/guizimo/p/13613311.html
Copyright © 2020-2023  润新知