【力扣-二叉树】8、二叉树的所有路径(257) 257 二

「这是我参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战

257. 二叉树的所有路径

题目描述

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

示例 1:

1
2
css复制代码输入: root = [1,2,3,null,5]
输出: ["1->2->5","1->3"]

示例 2:

1
2
css复制代码输入: root = [1]
输出: ["1"]

解析

求解路径问题

  • 递归法
    • 使用前序遍历
    • 确定递归函数的参数与返回值
    • 确定递归终止的条件
    • 单层递归的逻辑实现
  • 迭代法
    • 使用前序遍历
    • 定义存放节点的栈
    • 定义存放路径的栈
    • 迭代更新栈中的节点与路径

递归法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
c++复制代码class Solution
{

public:
vector<string> binaryTreePaths(TreeNode *root)
{

vector<string> result;
vector<int> path;
if (root == NULL)
{
return result;
}
traversal(root, path, result);

return result;
}

private:
// 1、确定递归函数的参数与返回值
// 参数:传入的根节点,记录的路径path ,存放结果集的result
void traversal(TreeNode *cur, vector<int> &path, vector<string> &result)
{
// 将当前节点存入到path中
path.push_back(cur->val);
// 2、确定递归的终止条件
// 左右孩子节点为空则说明当前节点为叶子节点,可以终止本次遍历
if (cur->left == NULL && cur->right == NULL)
{
string strPath;
// 先加入前n-1个节点,这里不包括path中的最后一个节点
for (int i = 0; i < path.size() - 1; i++)
{
strPath += to_string(path[i]);
strPath += "->";
}

// 加入每个路径的最后一个节点
strPath += to_string(path[path.size() - 1]);
result.push_back(strPath);
return;
}

// 3、单层递归的逻辑
// 采用前序遍历,所以先处理中间节点,中间节点就是要记录的路径中的节点,使用path存放
// 然后是递归与回溯过程
// 节点为空的时候就不进行递归与回溯了

if (cur->left)
{
traversal(cur->left, path, result);
path.pop_back(); // 回溯
}
if (cur->right)
{
traversal(cur->right, path, result);
path.pop_back(); // 回溯
}
}
};

迭代法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
c++复制代码// 迭代法
// 前序遍历
// 定义两个栈
// 一个栈用来存放 遍历路径中的节点
// 一个栈用来存放 遍历的路径
class Solution
{
public:
vector<string> binaryTreePaths(TreeNode *root)
{
// 存放节点的栈
stack<TreeNode *> nodePath;
// 存放路径的栈
stack<string> strPath;
// 结果数组
vector<string> result;
if (root == NULL)
{
return result;
}

// 将根节点入栈
nodePath.push(root);
// 根节点作为路径的起点
strPath.push(to_string(root->val));

// 迭代
while (!nodePath.empty())
{
// 取出当前节点(中)
TreeNode *node = nodePath.top();
nodePath.pop();

// 取出节点对应的路径
string path = strPath.top();
strPath.pop();

// 遇到叶子节点,将当前节点的路径存入到结果集中
if (node->left == NULL && node->right == NULL)
{
result.push_back(path);
}
// 左节点
if (node->left)
{
nodePath.push(node->left);
strPath.push(path + "->" + to_string(node->left->val));
}
// 右节点
if (node->right)
{
nodePath.push(node->right);
strPath.push(path + "->" + to_string(node->right->val));
}
}
return result;
}
};

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%