Binary Tree Paths

该博客探讨了如何在二叉树中找到从根节点到叶节点的路径。通过递归方法,针对每个节点判断是否为叶节点及是否为根节点,从而获取有效的路径。

地址:点击打开链接

得到路径的时候判断一下叶节点,然后对是不是根节点判断一下,再用递归的方法


答案:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if root == None:
            return []
        if not root.left and not root.right:
            return [str(root.val)]
        self.pathList = []
        self.getTreePath(root,'')
        return self.pathList
    def getTreePath(self,root,path):
        if root == None:
            return path
        if not root.left and not root.right:
            if path == '':
                path = str(root.val)
            else:
                path += '->' + str(root.val)
            self.pathList.append(path)
        else:
            if path == '':
                path = str(root.val)
            else:
                path += '->' + str(root.val)
            self.getTreePath(root.left, path )
            self.getTreePath(root.right, path)


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`函数查找满足条件的路径,并输出结果。最后释放二叉树内存。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值