Binary Tree Paths

本文介绍了一种使用先序遍历方法寻找二叉树所有根到叶子节点路径的算法。通过递归函数实现字符串拼接,当遇到叶子节点时,将路径字符串处理为指定格式并存入结果集合。该算法适用于所有类型的二叉树。

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:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

 

思路:采用先序遍历的方法,每次先把字符串加起来(传下去,因此递归函数还需要一个当前字符串),判断如果没有孩子了,则将字符串处理成要求格式,加到集合里;如果有左,则递归遍历左;如果有右,则递归遍历右。

/**
 * 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>re;
		if (!root)
			return re;
		Paths(root, re, "");
		return re;


	}
	void Paths(TreeNode* root, vector<string>&re, string s)
	{
		//s用来记录上一次
		
		s = s+"->"+to_string(root->val);//每次先用空格隔开
		if (!root->left&&!root->right)
			//去掉最开始的箭头
			re.push_back(s.substr(2));
		//去除两端空格,并把中间的空格 用箭头替代
		//类似先序遍历,现在处理左
		if (root->left)
			Paths(root->left, re, s);
		if (root->right)
			Paths(root->right, re, s);



	}


};
Binary Tree Paths with Sum Equal to a Certain Value Score: 30 Author: Zhu Yungang Institution: Jilin University Given a binary tree where the nodes are non-zero integers, given an integer K, write a program to find all paths starting from the root node and ending at leaf nodes where the sum of the node values ​​equals K. For example, if K=15, for the binary tree t shown below, there are 2 paths that satisfy the condition: 8-5-2 and 8-7. If no path satisfies the condition, it should still be recognized. img.jpg Input Format: The input consists of two lines. The first line contains a set of space-separated integers, not exceeding 100, representing the preorder sequence of the binary tree with null pointer information (represented by 0). The second line is an integer K. Output Format: The first line of the output is an integer representing the number of paths that satisfy the condition; if no path satisfies the condition, output 0. Starting from the second line, each line represents a path that meets the condition. If multiple paths meet the condition, output them sequentially from left to right. Each node value in the path is followed by a space. If two different paths contain exactly the same node values, both must be output. Input Example 1: 8 5 1 0 0 2 0 0 7 0 0 15 Output Example 1: 2 8 5 2 8 7 Input Example 2: -1 2 0 0 3 0 0 2 Output Example 2: 1 -1 3 Input Example 3: 1 1 0 0 1 0 0 2 Output Example 3: 2 1 1 1 1 Input Example 4: -1 2 0 0 3 0 0 8 Output Example 4: 0C++
最新发布
11-08
以下是一个C++程序,用于查找二叉树中从根节点到叶节点且节点值之和等于给定整数`K`的所有路径,并按指定输入输出格式处理。 ```cpp #include <iostream> #include <vector> // 定义二叉树节点结构 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; // 辅助函数,用于递归查找路径 void findPaths(TreeNode* root, int target, std::vector<int>& currentPath, std::vector<std::vector<int>>& result) { if (!root) return; // 将当前节点加入路径 currentPath.push_back(root->val); // 如果是叶子节点且路径和等于目标值 if (!root->left && !root->right && root->val == target) { result.push_back(currentPath); } // 递归查找左子树和右子树 findPaths(root->left, target - root->val, currentPath, result); findPaths(root->right, target - root->val, currentPath, result); // 回溯,移除当前节点 currentPath.pop_back(); } // 主函数,查找所有满足条件的路径 std::vector<std::vector<int>> pathSum(TreeNode* root, int sum) { std::vector<std::vector<int>> result; std::vector<int> currentPath; findPaths(root, sum, currentPath, result); return result; } // 辅助函数,根据输入数组构建二叉树 TreeNode* buildTree(const std::vector<int>& values, int index) { if (index >= values.size() || values[index] == 0) return nullptr; TreeNode* node = new TreeNode(values[index]); node->left = buildTree(values, 2 * index + 1); node->right = buildTree(values, 2 * index + 2); return node; } // 辅助函数,释放二叉树内存 void freeTree(TreeNode* root) { if (!root) return; freeTree(root->left); freeTree(root->right); delete root; } int main() { // 示例输入:节点值数组和目标和K std::vector<int> values = {5, 4, 8, 11, 0, 13, 4, 7, 2, 0, 0, 0, 0, 5, 1}; int K = 22; // 构建二叉树 TreeNode* root = buildTree(values, 0); // 查找满足条件的路径 std::vector<std::vector<int>> paths = pathSum(root, K); // 输出结果 for (const auto& path : paths) { for (int val : path) { std::cout << val << " "; } std::cout << std::endl; } // 释放二叉树内存 freeTree(root); return 0; } ``` ### 代码解释 1. **TreeNode结构体**:定义了二叉树的节点结构,包含节点值`val`,以及左右子节点指针`left`和`right`。 2. **findPaths函数**:递归地查找从根节点到叶节点且节点值之和等于目标值的路径。在递归过程中,将当前节点加入路径,并递归查找左子树和右子树。如果是叶子节点且路径和等于目标值,则将该路径加入结果集。最后进行回溯,移除当前节点。 3. **pathSum函数**:调用`findPaths`函数,返回所有满足条件的路径。 4. **buildTree函数**:根据输入的节点值数组构建二叉树。 5. **freeTree函数**:释放二叉树占用的内存,防止内存泄漏。 6. **main函数**:示例输入节点值数组和目标和`K`,构建二叉树,调用`pathSum`函数查找满足条件的路径,并输出结果。最后释放二叉树内存。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值