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

    257. 二叉树的所有路径

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

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

    示例:

    输入:

       1
     /   
    2     3
     
      5
    

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

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

    /**
     * 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) {
            String path=new String("");
            List<String> list = new ArrayList<>();
            helper(root,path,list);
            return list;
        }
    
        public void helper(TreeNode root,String path,List<String> paths)
        {
            if(root!=null)
            {
                path+=Integer.toString(root.val);
                if(root.left==null && root.right == null)
                    paths.add(path);
                else{
                    path+="->";
                    helper(root.left,path,paths);
                    helper(root.right,path,paths);
                }
            }
        }
    }
    
  • 相关阅读:
    数据的追踪审计
    通知模块设计
    数据库'tempdb' 的事务日志已满处理方法
    三级联动
    组合查询
    用户控件
    MDI容器
    控件说明
    winfrom
    自动生成编号
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075307.html
Copyright © 2011-2022 走看看