# 二叉树的所有路径

44人阅读 评论(0)

   1
/   \
2     3
\
5


[
"1->2->5",
"1->3"
]

/**

* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
* 根左右 遍历
*/
public List<String> binaryTreePaths(TreeNode root) {
// Write your code here
ArrayList<String> paths = new ArrayList<String>();
String path = "";
if (root == null){
return paths;
}
searchPaths(root, paths, path);
return paths;
}
public void searchPaths(TreeNode root, ArrayList<String> paths, String path){
if (root == null){
return;
}
if (root.left == null && root.right == null){
if (path.equals("")){
path += root.val;
}
else {
path += "->" + root.val;
}
}
//非叶子节点 将节点加入字符串保存
if (path.equals("")){
path += root.val;
}
else {
path += "->" + root.val;
}
searchPaths(root.left, paths, path);
searchPaths(root.right, paths, path);
}
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：8070次
• 积分：942
• 等级：
• 排名：千里之外
• 原创：91篇
• 转载：0篇
• 译文：0篇
• 评论：2条
最新评论