257. Binary Tree Paths

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"]
题目含义:找到所有从根到叶子加点的路径
 1      public void appendChildren(TreeNode root,String curPath,List<String> answer) {
 2         if (root == null) return;
 3         if (root.left== null && root.right==null) answer.add(curPath+root.val);
 4         if (root.left!=null) appendChildren(root.left,curPath+root.val+"->",answer);
 5         if (root.right!=null) appendChildren(root.right,curPath+root.val+"->",answer);
 6     }   
 7     
 8     public List<String> binaryTreePaths(TreeNode root) {
 9          if(root == null) return new ArrayList<String>();
10         List<String> result = new ArrayList<>();
11         appendChildren(root,"",result);   
12         return result;
13     }

 

以上是关于257. Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章

Java [Leetcode 257]Binary Tree Paths

257. Binary Tree Paths

LeetCode257. Binary Tree Paths 解题报告

257. Binary Tree Paths

257.Binary Tree Paths

257. Binary Tree Paths