(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);
        }
    }
    
}

  

运行结果:

      

原文地址:https://www.cnblogs.com/mlz-2019/p/4734005.html