问题描述:
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
打印二叉树的路径(实际上不是打印,存在list里面)
思路:
我们需要调用一个方法,这个方法需要有以下参数:根节点,初始路径字符串,容器。
根节点是所有路径的起始点,是root
初始路径字符串是空字符串,因为一开始没有加入任何节点
容器是我们要返回的list
首先我们要加入根节点
其次,我们要判断这个根节点是不是叶子节点,如果是的话就要考虑添加进容器里;如果不是的话,说明我们会有更多的点加入目前的路径,所以我们要先添加一个"->",然后取决于哪一侧可以继续,我们可以发现子问题:即套用相同的方法只不过根节点变为这个根节点的左/右孩子(递归)
代码如下:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list=new ArrayList<>();
constructPath(root, "", list);
return list;
}
private void constructPath(TreeNode root, String path, List<String> list){
//add the root
path=path+Integer.toString(root.val);
//if reach the leaf, add the path
if((root.left==null)&&(root.right==null)){
list.add(path);
}
//otherwise we cannot add the path, but continue adding nodes to path
else{
path=path+"->";
//depends on which direcxtion it has nodes to add
if(root.left!=null){
constructPath(root.left, path, list);
}
if(root.right!=null){
constructPath(root.right, path, list);
}
}
}
}
时间复杂度: O(n), 因为每一个节点访问一遍