zoukankan      html  css  js  c++  java
  • (easy)LeetCode 257.Binary Tree Paths

    Given a binary tree, return all root-to-leaf paths.

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    ["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; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
           List<String> ret=new ArrayList<>();
           if(root==null) return ret;
           String s=""+root.val;
           paths(root,s,ret);
           return ret;
        }
        public void paths(TreeNode root,String s,List<String>ret){
            if(root.left==null && root.right==null){
                ret.add(s);
            }
            else{
                if(root.left!=null) paths(root.left,s+"->"+root.left.val,ret);
                if(root.right!=null) paths(root.right,s+"->"+root.right.val,ret);
            }
        }
        
    }
    

      

    运行结果:

          

  • 相关阅读:
    centos6.8升级python3.5.2
    钓鱼
    斯诺登的密码
    模板,堆,小根堆
    哥德巴赫猜想(升级版)
    哥德巴赫猜想
    线性筛素数
    乒乓球
    数的重心模板
    笨小猴
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4734005.html
Copyright © 2011-2022 走看看