这道题的解题思路可以使用深度遍历或者广度遍历。 首先采用深度遍历,在深度优先搜索遍历二叉树时,我们需要考虑当前的节点以及它的孩子节点。 1.如果当前节点不是叶子节点,则在当前的路径末尾添加该节点,并继续递归遍历该节点的每一个孩子节点。 2.如果当前节点是叶子节点,则在当前路径末尾添加该节点后*将该路径加入到结果中。 如此,当遍历完整棵二叉树以后我们就得到了所有从根节点到叶子节点的路径。
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> paths = new ArrayList<String>(); constructPaths(root, "", paths); return paths; } public void constructPaths(TreeNode root, String path, List<String> paths) { if (root != null) { StringBuffer pathSB = new StringBuffer(path); pathSB.append(Integer.toString(root.val)); if (root.left == null && root.right == null) { // 当前节点是叶子节点 paths.add(pathSB.toString()); // 把路径加入到答案中 } else { pathSB.append("->"); // 当前节点不是叶子节点,继续递归遍历 constructPaths(root.left, pathSB.toString(), paths); constructPaths(root.right, pathSB.toString(), paths); } } } }那换成广度遍历需要怎样完成呢? 我们可以先建两个队列,一个队列nodeQueue用来存储结点,另一个队列pathQueue用来存储路径。 接着我们先判断当前节点是否为叶子结点,若是,则将此结点加入到pathQueue后就添加到List中。 若不是叶子结点,则将其子节点存入nodeQueue,并写进pathQueue中。 当队列为空时广度优先搜索结束,我们即能得到答案。
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> paths = new ArrayList<>(); //ConstuctPath(root,"",paths); if(root == null){ return paths; } Queue<TreeNode> nodeQueue = new LinkedList<>(); Queue<String> pathQueue = new LinkedList<>(); nodeQueue.offer(root); pathQueue.offer(Integer.toString(root.val)); while(!nodeQueue.isEmpty()){ TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); if(node.left == null && node.right == null){ paths.add(path); }else{ if(node.left!=null){ nodeQueue.offer(node.left); pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString()); } if(node.right!=null){ nodeQueue.offer(node.right); pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString()); } } } return paths; }