【LeetCode】257.Binary Tree Paths(Easy)解题报告
2018-03-11 10:27
465 查看
【LeetCode】257.Binary Tree Paths(Easy)解题报告
题目地址:https://leetcode.com/problems/binary-tree-paths/description/
题目描述:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
返回所有路径。
Solution:
Date:2018年3月11日
题目地址:https://leetcode.com/problems/binary-tree-paths/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 paths are: ["1->2->5", "1->3"]
返回所有路径。
Solution:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } 递归遍历就可以了 time : O(n) space : O(n) */ class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if(root == null) return res; helper(res,root,""); return res; } public void helper(List<String> res, TreeNode root,String path){ if(root.left == null && root.right == null){ res.add(path + root.val); } if(root.left!=null){ helper(res,root.left,path + root.val+"->"); } if(root.right!=null){ helper(res,root.right,path+root.val+"->"); } } }
Date:2018年3月11日
相关文章推荐
- 【LeetCode】110. Balanced Binary Tree(Easy)解题报告
- 【LeetCode】121.Best Time to Buy and Sell Stock(Easy)解题报告
- LeetCode解题报告 169. Majority Element [easy]
- 【LeetCode】687.Longest Univalue Path(Easy)解题报告
- 【LeetCode】104.Maximum Depth of Binary Tree(Easy)解题报告
- LeetCode】101.Symmetric Tree(Easy)解题报告
- LeetCode解题报告 101. Symmetric Tree [easy]
- 【LeetCode】122.Best Time to Buy and Sell Stock II(Easy)解题报告
- 【LeetCode】581.Shortest Unsorted Continuous Subarray(easy)解题报告
- 【LeetCode】401.Binary Watch(easy)解题报告
- 【LeetCode】617.Merge Two Binary Trees(Easy)解题报告
- 【LeetCode】108.Convert Sorted Array to Binary Search Tree(Easy)解题报告
- 【LeetCode】100.Same Tree(Easy)解题报告
- 【LeetCode】448.Find All Numbers Disappeared in an Array(Easy)解题报告
- 【LeetCode】112.Path Sum(Easy)解题报告
- 【LeetCode】226.Invert Binary Tree(Easy)解题报告
- 【LeetCode】637.Average of Levels in Binary Tree(Easy)解题报告
- 【LeetCode】572.Subtree of Another Tree(Easy)解题报告
- LeetCode解题报告 112. Path Sum [easy]
- LeetCode】66.Plus One(easy)解题报告