LeetCode 257. 二叉树的所有路径

题目描述

🔥 257. 二叉树的所有路径

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func binaryTreePaths(root *TreeNode) []string {
	res := make([]string, 0)
	if root == nil {
		return res
	}
	dfs(root, "", &res)
	return res
}

func dfs(node *TreeNode, path string, res *[]string) {
	if node == nil {
		return
	}
	if node.Left == nil && node.Right == nil {
		*res = append(*res, path+strconv.Itoa(node.Val))
	}
	dfs(node.Left, path+strconv.Itoa(node.Val)+"->", res)
	dfs(node.Right, path+strconv.Itoa(node.Val)+"->", res)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
type QueueNode struct {
	Node *TreeNode
	Path string
}

func binaryTreePaths(root *TreeNode) []string {
	res := make([]string, 0)
	if root == nil {
		return res
	}
	queue := []*QueueNode{&QueueNode{
		Node: root,
		Path: strconv.Itoa(root.Val),
	}}
	for len(queue) > 0 {
		node, path := queue[0].Node, queue[0].Path
		queue = queue[1:]
		if node.Left == nil && node.Right == nil {
			res = append(res, path)
		}
		if node.Left != nil {
			queue = append(queue, &QueueNode{
				Node: node.Left,
				Path: path + "->" + strconv.Itoa(node.Left.Val),
			})
		}
		if node.Right != nil {
			queue = append(queue, &QueueNode{
				Node: node.Right,
				Path: path + "->" + strconv.Itoa(node.Right.Val),
			})
		}
	}
	return res
}

🍏 点击查看 Java 题解

1
write your code here

相似题目

题目 难度 题解
路径总和 II Medium  
从叶结点开始的最小字符串 Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/53054646
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!