257 Binary Tree Paths¶
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
Solution: Recursion¶
Time complexity: O(n) Space complexity: O(n) / output can be O(n^2)
/**
* 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> result = new LinkedList<String>();
process(root, "", result);
return result;
}
private void process(TreeNode node, String curr, List<String> result) {
if (node == null) {
return;
}
String next = curr + "->" + node.val;
if (node.left == null && node.right == null) {
result.add(next.substring(2));
}
process(node.left, next, result);
process(node.right, next, result);
}
}
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
string s;
function<void(TreeNode*, int)> preorder = [&](TreeNode* node, int l) {
if (!node) return;
s += (l > 0 ? "->" : "") + to_string(node->val);
if (!node->left && !node->right)
ans.push_back(s);
preorder(node->left, s.size());
preorder(node->right, s.size());
while (s.size() != l) s.pop_back();
};
preorder(root, 0);
return ans;
}
};