Skip to content
本页目录

0257-二叉树的所有路径

https://leetcode.cn/problems/binary-tree-paths

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。 叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]

示例 2:

输入:root = [1]
输出:["1"]

提示:

树中节点的数目在范围 [1, 100] 内
-100 <= Node.val <= 100

思路

dfs深度优先搜索,搜索时加入数据到list中,当发现到叶子节点就输出到结果集中。

参考代码

csharp
public class Solution {
	List<string> result = new List<string>();
	private void dfs(TreeNode root, List<int> list){
		if(root == null){
			return;
		}
		list.Add(root.val);

		if(root.left == null && root.right == null){
			//输出
			string s = "";
			for(int i=0; i<list.Count; i++){
				s += i == 0 ? list[i] : "->"+list[i];
			}
			result.Add(s);
		}

		dfs(root.left,list);
		dfs(root.right,list);

		list.RemoveAt(list.Count-1);
	}

    public IList<string> BinaryTreePaths(TreeNode root) {
    	List<int> list = new List<int>();
    	dfs(root,list);
    	return result;
    }
}

Released under the MIT License.