Leetcode depth-first search for all paths in a binary tree java

Title description
Given a binary tree, return all the paths from the root node to the leaf nodes.

If the current node is empty, return directly.
If it is a leaf node (that is, the left and right subtrees are empty), it means that a path is found and added to res.
If it is not a leaf node, continue to traverse its left and right child nodes respectively

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public List<String> binaryTreePaths(TreeNode root) {
    
    
        List<String> res = new ArrayList<>();
        dfs(root,"",res);
        return res;
    }
    void dfs(TreeNode root,String path,List<String> res){
    
    
        if(root == null){
    
    
            return;
        }
        if(root.left == null && root.right == null){
    
    
            res.add(path+root.val);
            return;
        }
        dfs(root.left,path+root.val+"->",res);
        dfs(root.right,path+root.val+"->",res);
    }
}

Guess you like

Origin blog.csdn.net/stonney/article/details/110354537