Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
Approach #1: C++. [recursive]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if (root == NULL) return ans;
helper(root, ans, "");
return ans;
}
private:
void helper(TreeNode* root, vector<string>& ans, string str) {
if (root == NULL) return;
if (str == "") str += to_string(root->val);
else str += "->" + to_string(root->val);
if (root->left == NULL && root->right == NULL)
ans.push_back(str);
helper(root->left, ans, str);
helper(root->right, ans, str);
}
};
Approach #2: Java. [dfs + stack]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root == null) return ans;
Stack<TreeNode> sNode = new Stack<>();
Stack<String> sStr = new Stack<>();
sNode.push(root);
sStr.push("");
while (!sNode.isEmpty()) {
TreeNode curNode = sNode.pop();
String curStr = sStr.pop();
if (curNode.left == null && curNode.right == null) ans.add(curStr+curNode.val);
if (curNode.left != null) {
sNode.push(curNode.left);
sStr.push(curStr + curNode.val + "->");
}
if (curNode.right != null) {
sNode.push(curNode.right);
sStr.push(curStr + curNode.val + "->");
}
}
return ans;
}
}
Appraoch #3: Python. [bfs + queue]
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
res, queue = [], collections.deque([(root, "")])
while queue:
node, ls = queue.popleft()
if not node.left and not node.right:
res.append(ls + str(node.val))
if node.left:
queue.append((node.left, ls + str(node.val) + "->"))
if node.right:
queue.append((node.right, ls + str(node.val) + "->"))
return res