-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePath.java
More file actions
56 lines (43 loc) · 1001 Bytes
/
Copy pathBinaryTreePath.java
File metadata and controls
56 lines (43 loc) · 1001 Bytes
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.wgcris.LeetcodeAlgorithm;
import java.util.ArrayList;
import java.util.List;
/*
* 257 二叉树的路径:从根节点到叶节点
*
* For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
*/
public class BinaryTreePath {
/**
* 深度优先算法
* @param root
* @return
*/
public static List<String> res=new ArrayList<>();
public static List<String> binaryTreePaths(TreeNode root){
if(root!=null) findpath(root, String.valueOf(root.data));
return res;
}
/**
* 典型的深度优先算法,回溯法
* @param node
* @param path
*/
public static void findpath(TreeNode node,String path){
if(node.left==null && node.right==null) res.add(path);
if(node.left!=null) findpath(node.left, path+"->"+node.left.data);
if(node.right!=null)findpath(node.right, path+"->"+node.right.data);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}