257. Binary Tree Paths

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 of String, 看了答案发现了一些以前不知道的表达。比如root.val + ""就表示一个String,字符串内容是root.val。 这道题用DFS做,递归的定义是:当前路径下,如果该节点是叶节点,则将该路径加入到res里;如果该节点不是叶节点,则继续遍历其左右节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<String> res = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {   
        if (root == null){
            return res;            
        }
        helper(root, root.val + "");
        return res;
    }
    private void helper(TreeNode root, String path){
        if (root.left == null && root.right == null){
            res.add(path);
        }    
        if (root.left != null){
            helper(root.left, path + "->" + root.left.val);
        }
        if (root.right != null){
            helper(root.right, path + "->" + root.right.val);
        }      
    } 
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容