File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text ;
5
+
6
+ namespace Tree . TreeLib
7
+ {
8
+ public class TreePaths
9
+ {
10
+ //Given a binary tree, return all root-to-leaf paths.
11
+ //For example, given the following binary tree:
12
+ // 1
13
+ // / \
14
+ //2 3
15
+ // \
16
+ // 5
17
+ //All root-to-leaf paths are:
18
+ //["1->2->5", "1->3"]
19
+ public IList < string > BinaryTreePaths ( TreeNode root )
20
+ {
21
+ if ( root == null )
22
+ return new List < string > ( ) ;
23
+ if ( root . left == null && root . right == null )
24
+ return new List < string > { root . val . ToString ( ) } ;
25
+ IList < string > rtn = new List < string > ( ) ;
26
+ IList < string > rtnleft = BinaryTreePaths ( root . left ) ; //左子树路径
27
+ foreach ( var item in rtnleft ) //左子树都继承于根节点
28
+ rtn . Add ( root . val + "->" + item ) ;
29
+ IList < string > rtnright = BinaryTreePaths ( root . right ) ;
30
+ foreach ( var item in rtnright )
31
+ rtn . Add ( root . val + "->" + item ) ;
32
+ return rtn ;
33
+ }
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments