LeetCode 257 Binary Tree Paths (DFS)

来源:互联网 发布:星星知我心幼年弯弯 编辑:程序博客网 时间:2024/05/16 08:23

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即可 (16ms 击败76%)

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


原创粉丝点击