257-Binary Tree Paths

kevin聰發表於2018-05-02

Description

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 p

All root-to-leaf paths are:

["1->2->5", "1->3"]

問題描述

給定二叉樹嗎, 返回所有根節點到葉子節點的路徑


問題分析

先序遍歷, 儲存臨時變數path, 記錄路徑, 當前節點為葉子節點時將path新增入res中即可


解法

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList();
        if(root == null) return res;

        dfs(root, res, "");

        return res;

    }
    public void dfs(TreeNode root, List<String> res, String path){
        if(root == null) return;

        if(root.left == null && root.right == null) res.add(path + root.val);

        dfs(root.left, res, path + root.val + "->");
        dfs(root.right, res, path + root.val + "->");
    }
}

相關文章