Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
解题思路:建立一个新的ArrayList,站在root,左右分别处理,然后左右两边分别定义一个path来存储左子树再加上根节点,最后判断是否为叶子节点。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>(); //1.此处应有() 2. list不能实例化,得用arraylist进行实例化
if(root==null){
return result;
}
//divide
List<String> leftpath=binaryTreePaths(root.left);
List<String> rightpath=binaryTreePaths(root.right);
//conquer
for (String path:leftpath){//在这里定义一个path来存储左子树
result.add(root.val+"->"+path);//根节点的值->左子树
}
for (String path:rightpath){
result.add(root.val+"->"+path);
}
//leaf node
if(root.left==null&&root.right==null){//判断叶子节点
result.add(root.val+"");
}
return result;
}
}