标签:
题目:
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"]
链接: http://leetcode.com/problems/binary-tree-paths/
题解:
求Binary Tree所有路径。用Recursive解法会比较容易。逻辑是,假如为current root为leaf node,则在res中加入该节点,返回。否则,递归求解,在左子树和右子树每一个结果中,在String前面insert root.val + "->"。
Time Complexity - O(n), Space Complexity - O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if(root == null) return res; if(root.left == null && root.right == null) { res.add(String.valueOf(root.val)); } else { for(String s : binaryTreePaths(root.left)) { res.add(String.valueOf(root.val) + "->" + s); } for(String s : binaryTreePaths(root.right)) { res.add(String.valueOf(root.val) + "->" + s); } } return res; } }
Reference:
https://leetcode.com/discuss/65362/my-concise-java-dfs-solution
https://leetcode.com/discuss/55451/clean-solution-accepted-without-helper-recursive-function
https://leetcode.com/discuss/52072/accepted-java-simple-solution-in-8-lines
https://leetcode.com/discuss/52020/5-lines-recursive-python
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5014959.html