257. Binary Tree Paths
Problem:
Typical DFS, but to remember the ending condition is root.left == null and root.right == null.
Solution:
After some optimization of code structure;
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"]Analysis:
Typical DFS, but to remember the ending condition is root.left == null and root.right == null.
Solution:
After some optimization of code structure;
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if (root == null) return res; dfs(root, new StringBuilder(), res); return res; } private void dfs(TreeNode root, StringBuilder sb, List<String> res) { if (root == null) return; int len = sb.length(); sb.append(Integer.toString(root.val)); if (root.left == null && root.right == null) { res.add(sb.toString()); } else { sb.append("->"); dfs(root.left, sb, res); dfs(root.right, sb, res); } sb.setLength(len); } }
评论
发表评论