[LeetCode] 257. 二叉树的所有路径

递归遍历:
1、root为空时,直接返回;
2、当左右子树都为空时,节点为叶子节点,将路径添加到结果数组。
3、分别递归遍历左右子树。
Python解法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = ""
out = []
def backtrack(root, res):
if not root: return
if not root.left and not root.right:
res += str(root.val)
out.append(res)
return
res += str(root.val) + '->'
if root.left:
backtrack(root.left, res)
if root.right:
backtrack(root.right, res)
backtrack(root, "")
return out
C++版本
/**
* 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:
void DFS(TreeNode* root, string str, vector<string> &res)
{
if(root==NULL)
return;
if(!root->left && !root->right)
{
str+=to_string(root->val);
res.push_back(str);
return;
}
str+=to_string(root->val)+"->";
DFS(root->left,str,res);
DFS(root->right,str,res);
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> res;
string str;
DFS(root,str,res);
return res;
}
};
这篇博客介绍了如何使用递归方法遍历二叉树并找出所有从根节点到叶节点的路径。提供了Python和C++两种语言的解决方案,通过构建字符串并在遍历过程中添加连接符来构造路径。在Python中,使用了backtrack函数进行深度优先搜索,而在C++中,使用了DFS函数达到相同目的。
1134

被折叠的 条评论
为什么被折叠?



