首页 > 其他 > 详细

[LeetCode]257. 二叉树的所有路径

时间:2020-06-04 01:27:55      阅读:32      评论:0      收藏:0      [点我收藏+]

题目

给定一个二叉树,返回所有从根节点到叶子节点的路径。
例:输出: ["1->2->5", "1->3"]

题解

  • 递归。
  • 重点是参数的设置:为Root,路径字符串,路径List集合。
  • 首先判断root!=null,然后根据是否为叶子结点做不同操作。

代码

/**
 * 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> list = new LinkedList<>();
        String s = "";
        getPaths(root,s,list);
        return list;
    }

    public void getPaths(TreeNode root,String path,List<String> ans){
        if(root!=null){
            path+=root.val;
            if(root.left==null&&root.right==null){
                ans.add(path);
            }
            else{
                path+="->";
                getPaths(root.left,path,ans);
                getPaths(root.right,path,ans);
            }
        }
    }
}

[LeetCode]257. 二叉树的所有路径

原文:https://www.cnblogs.com/coding-gaga/p/13040965.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!