Skip to content

Commit 5744be6

Browse files
committed
257.bindary tree paths
1 parent 552fd23 commit 5744be6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Tree/Tree.TreeLib/TreePaths.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)