leetcode 257. Binary Tree Paths(DFS)

問題描述:

  Given a binary tree, return all root-to-leaf paths.

  For example, given the following binary tree:


這裏寫圖片描述

代碼:

/**
 * 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> result = new ArrayList<>();
        if(root == null) return result;
        String s = "";
        dfs(root, s, result);
        return result;
    }

    public void dfs(TreeNode root, String s, List<String> result){
        s += root.val;
        if(root.left == null && root.right == null)
            result.add(s);
        if(root.left != null){
            dfs(root.left, s+"->", result);            
        }
        if(root.right != null)
            dfs(root.right, s+"->", result);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章