257. Binary Tree Paths

本文介绍了一种使用深度优先搜索(DFS)算法遍历二叉树并找出所有从根节点到叶子节点路径的方法。通过递归实现,文章提供了两种不同的C++实现方案,并对比了它们之间的差异。

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

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

使用DFS,因为需要使用到递归,必须要指定递归出口,对于这个情况,递归出口就是叶子节点。

先贴出我自己写的low代码。。。

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        if (root == NULL) return result;
        string out = "";
        DFS(root, result, out);
        return result;
    }
    void DFS(TreeNode* root, vector<string>& result, string& out) {
        if (root->left == NULL && root->right == NULL) {
            out += to_string(root->val);
            cout << out;
            result.push_back(out);
            return;
        } else {
            if (root->left != NULL) {
                string oldStr = out;
                out += to_string(root->val) + "->";
                DFS(root->left, result, out);
                out = oldStr;
            }
            if (root->right != NULL) {
                string oldStr = out;
                out += to_string(root->val) + "->";
                DFS(root->right, result, out);
                out = oldStr;
            }
        }
    }
}
这个题发现了一个情况,就是如果在DFS中使用string& out,调用DFS的时候不能传入“”(空字符串),必须定义初始化。

然后在再传Grandyang的代码:

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        if (root == NULL) return result;
        string out = "";
        DFS(root, result, "");
        return result;
    }
   
    void DFS(TreeNode* root, vector<string>& result, string out) {
        out += to_string(root->val);
        if (root->left == NULL && root->right == NULL) {
            result.push_back(out);
        } else {
            if (root->left != NULL) DFS2(root->left, result, out + "->");
            if (root->right != NULL) DFS2(root->right, result, out + "->");
        }
    }
    
};
简洁的一逼啊。。。。还是要继续努力。。共勉!


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、付费专栏及课程。

余额充值