给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
思路:深度优先搜索 DFS
Python
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def binaryTreePaths(root):
if not root:
return []
ans = []
left = binaryTreePaths(root.left)
right = binaryTreePaths(root.right)
if not root.left and not root.right:
return [str(root.val)]
for data in left + right:
ans.append(str(root.val)+'->'+data)
return ans
C++
// Definition for a binary tree node.
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void dfs(TreeNode* root, string path, vector<string>& paths)
{
if (root != nullptr)
{
path += to_string(root->val);
if (root.left == nullptr and root.right == nullptr)
{
paths.emplace_back(path);
}
else
{
path += "->";
dfs(root->left, path, paths);
dfs(root->right, path, paths);
}
}
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> paths;
dfs(root, "", paths);
return paths;
}