DFS_257. 二叉树的所有路径

 

给定一个二叉树,返回所有从根节点到叶子节点的路径。

 

说明: 叶子节点是指没有子节点的节点。

 

示例:

输入:

1
/ \
2 3
\
5

输出: ["1->2->5", "1->3"]

 

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths


思路:

树的dfs算法相对图的dfs算法更容易理解一点,BFS也是树比较好理解

这里先看官方给的定义

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

每个节点都有他的左孩子或者右孩子,除非他是叶子节点

所以遍历就看是不是叶子节点就行了,不是叶子节点就递归,是叶子节点就记录该条路径,回溯

class Solution {
     public static LinkedList<String> dfs(TreeNode root, String way, LinkedList<String>path){
        if (root == null){
            return null;
        }else {
            //路径中加入该节点
            way += Integer.toString(root.val);
            // 当前节点是叶子节点
            if ((root.left == null) && (root.right == null)) 
                // 记录该条路径
                path.add(way);  
            else {
                way += "->";  // 当前节点不是叶子节点,继续递归遍历
                dfs(root.left, way, path);
                dfs(root.right, way, path);
            }
        }
        return path;
    }

    public List<String> binaryTreePaths(TreeNode root) {
        LinkedList<String> path = new LinkedList();
        dfs(root, "", path);
        return path;
    }        
}

 

posted @ 2020-07-24 11:51  _未知的暖意  阅读(142)  评论(0编辑  收藏  举报