mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0257.二叉树的所有路径,添加C#递归
This commit is contained in:
@ -900,6 +900,43 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
### C#
|
||||||
|
```C#
|
||||||
|
public IList<string> BinaryTreePaths(TreeNode root)
|
||||||
|
{
|
||||||
|
List<int> path = new();
|
||||||
|
List<string> res = new();
|
||||||
|
if (root == null) return res;
|
||||||
|
Traversal(root, path, res);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
public void Traversal(TreeNode node, List<int> path, List<string> res)
|
||||||
|
{
|
||||||
|
path.Add(node.val);
|
||||||
|
if (node.left == null && node.right == null)
|
||||||
|
{
|
||||||
|
string sPath = "";
|
||||||
|
for (int i = 0; i < path.Count - 1; i++)
|
||||||
|
{
|
||||||
|
sPath += path[i].ToString();
|
||||||
|
sPath += "->";
|
||||||
|
}
|
||||||
|
sPath += path[path.Count - 1].ToString();
|
||||||
|
res.Add(sPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (node.left != null)
|
||||||
|
{
|
||||||
|
Traversal(node.left, path, res);
|
||||||
|
path.RemoveAt(path.Count-1);
|
||||||
|
}
|
||||||
|
if (node.right != null)
|
||||||
|
{
|
||||||
|
Traversal(node.right, path, res);
|
||||||
|
path.RemoveAt(path.Count-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user