給一棵二叉樹,找出從根節點到葉子節點的所有路徑。
題目鏈接
可參考376題一起做
/**
* 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) {
List<String> list = new ArrayList<String>();
if(root != null) {
String temp = "" + root.val;
findWay(list, temp, root);
}
return list;
}
private void findWay(List<String> list, String way, TreeNode node) {
if(node.left != null && node.right != null) {
String copy = way.toString();
way = way + "->" + node.left.val;
copy = copy + "->" + node.right.val;
findWay(list, way, node.left);
findWay(list, copy, node.right);
} else if(node.left != null && node.right == null) {
way = way + "->" + node.left.val;
findWay(list, way, node.left);
} else if(node.left == null && node.right != null) {
way = way + "->" + node.right.val;
findWay(list, way, node.right);
} else {
list.add(way);
}
}
}