本文主要是介绍LeetCode 257 Binary Tree Paths (DFS),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;}
}
这篇关于LeetCode 257 Binary Tree Paths (DFS)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!