LeetCode题解: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"]

题意:给定一颗二叉树,返回所有从根节点到叶节点的路径

解决思路:DFS

代码:

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> path = new ArrayList<String>();
        if(root != null){
            dfs(root, "", path);
        }

        return path;
    }

    private void dfs(TreeNode root, String str, List<String> path){
        if(root.left == null && root.right == null){
            path.add(str + root.val);
        }

        if(root.left != null){
            dfs(root.left, str + root.val + "->", path);
        }

        if(root.right != null){
            dfs(root.right, str + root.val + "->", path);
        }
    }
}

你可能感兴趣的:(LeetCode题解:Binary Tree Paths)