題目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
思路:
題意:求二叉樹根到葉子的所有路徑二叉樹的問題,沒有一次遞歸解決不了的,如果有,那就兩次,判斷左右子樹,都為空是葉子節點,否則一直遞歸下去,然後傳入List參數和ArrayList參數
-
代碼:
public class Solution {
public List binaryTreePaths(TreeNode root) {
List all = new ArrayList();
if(root == null){
return all;
}
getTreePaths(all,new ArrayList(),root);
return all;
}
private void getTreePaths(List result,List tmp,TreeNode node){
if(node == null){
return;
}else{
tmp.add(node.val);
}
if(node.left == null && node.right == null){
result.add(getString(tmp));
}
if(node.left != null){
getTreePaths(result,new ArrayList(tmp),node.left);
}
if(node.right != null){
getTreePaths(result,new ArrayList(tmp),node.right);
}
}
private String getString(List tmp){
StringBuffer sb= new StringBuffer();
if(tmp == null||tmp.isEmpty()){
return null;
}
sb.append(tmp.get(0));
for(int i = 1;i < tmp.size();i++){
sb.append("->").append(tmp.get(i));
}
return sb.toString();
}
}