版權(quán)聲明:本文為博主原創(chuàng)文章沉填,未經(jīng)博主允許不得轉(zhuǎn)載。
難度:容易
要求:
給一棵二叉樹(shù),找出從根節(jié)點(diǎn)到葉子節(jié)點(diǎn)的所有路徑茉继。
樣例給出下面這棵二叉樹(shù):
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
List<String> list = new ArrayList<String>();
if(root != null){
addPath(root,String.valueOf(root.val), list);
}
return list;
}
public void addPath(TreeNode node,String path,List<String> list){
if(node == null){
return;
}
if(node.left == null && node.right == null){
list.add(path);
}
if(node.left != null){
addPath(node.left,path + "->" + String.valueOf(node.left.val),list);
}
if(node.right != null){
addPath(node.right,path + "->" + String.valueOf(node.right.val),list);
}
}
}