热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

打印二叉树的所有路径,每个路径中最大元素大于或等于K

打印二叉树的所有路径,每个路径中最大元素大于或等于 K原文:https://www . geesforgeks . org/pr

打印二叉树的所有路径,每个路径中最大元素大于或等于 K

原文:https://www . geesforgeks . org/print-每条路径中包含最大元素的二叉树的所有路径大于或等于 k/

给定一个二叉树和一个整数 K ,任务是打印从根到叶的路径,最大元素大于或等于 K 。如果没有这样的路径,打印-1。
举例:

Input: K = 25,
10
/ \
5 8
/ \ / \
29 2 1 98
/ \
20 50
Output: (10, 5, 29, 20), (10, 8, 98, 50)
Explanation:
The maximum value in the path 10
-> 5 -> 29 -> 20
is 29 which is greater than 25.
The maximum value in the path 10
-> 8 -> 98 -> 50
is 98 which is greater than 25.
Input: K = 5
2
/ \
1 4
/
0
Output: -1
Explanation:
None of the paths from the root to a leaf
has the value greater than 5.

方法:想法是检查节点是否包含大于或等于‘K’的值。如果是,则该节点的所有子树都是有效路径。可以按照以下步骤计算答案:


  • 对于每个节点,检查当前节点值是否大于“K”。

  • 如果是,则将其插入到向量中,并将标志变量设置为 1。这表示将打印通过该节点的所有路径。

  • 使用递归重复上述步骤。对左右子树递归调用该函数。

  • 最后,利用回溯的概念,从向量中打印路径。

以下是上述方法的实现:

卡片打印处理机(Card Print Processor 的缩写)

// C++ program to print paths with maximum
// element in the path greater than K
#include
using namespace std;
// A Binary Tree node
struct Node {
    int data;
    struct Node *left, *right;
};
// A utility function to create a new node
struct Node* newNode(int data)
{
    struct Node* newNode = new Node;
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return (newNode);
}
// A recursive function to print the paths
// whose maximum element is greater than
// or equal to K.
void findPathUtil(Node* root, int k,
                  vector path,
                  int flag, int& ans)
{
    if (root == NULL)
        return;
    // If the current node value is greater than
    // or equal to k, then all the subtrees
    // following that node will get printed,
    // flag = 1 indicates to print the required path
    if (root->data >= k)
        flag = 1;
    // If the leaf node is encountered, then the path is
    // printed if the size of the path vector is
    // greater than 0
    if (root->left == NULL && root->right == NULL) {
        if (flag == 1) {
            ans = 1;
            cout <<"(";
            for (int i = 0; i                 cout <            }
            cout <data <<"), ";
        }
        return;
    }
    // Append the node to the path vector
    path.push_back(root->data);
    // Recur left and right subtrees
    findPathUtil(root->left, k, path, flag, ans);
    findPathUtil(root->right, k, path, flag, ans);
    // Backtracking to return the vector
    // and print the path if the flag is 1
    path.pop_back();
}
// Function to initialize the variables
// and call the utility function to print
// the paths with maximum values greater than
// or equal to K
void findPath(Node* root, int k)
{
    // Initialize flag
    int flag = 0;
    // ans is used to check empty condition
    int ans = 0;
    vector v;
    // Call function that print path
    findPathUtil(root, k, v, flag, ans);
    // If the path doesn't exist
    if (ans == 0)
        cout <<"-1";
}
// Driver code
int main(void)
{
    int K = 25;
    /* Constructing the following tree:
                10
              /    \
             5      8
           /   \   /  \
          29    2 1    98
         /               \     
        20                50
   */
    struct Node* root = newNode(10);
    root->left = newNode(5);
    root->right = newNode(8);
    root->left->left = newNode(29);
    root->left->right = newNode(2);
    root->right->right = newNode(98);
    root->right->left = newNode(1);
    root->right->right->right = newNode(50);
    root->left->left->left = newNode(20);
    findPath(root, K);
    return 0;
}

Java 语言(一种计算机语言,尤用于创建网站)

// Java program to print paths with maximum
// element in the path greater than K
import java.util.*;
class GFG
{
// A Binary Tree node
static class Node
{
    int data;
    Node left, right;
};
static int ans;
// A utility function to create a new node
static Node newNode(int data)
{
    Node newNode = new Node();
    newNode.data = data;
    newNode.left = newNode.right = null;
    return (newNode);
}
// A recursive function to print the paths
// whose maximum element is greater than
// or equal to K.
static void findPathUtil(Node root, int k,
                Vector path,
                int flag)
{
    if (root == null)
        return;
    // If the current node value is greater than
    // or equal to k, then all the subtrees
    // following that node will get printed,
    // flag = 1 indicates to print the required path
    if (root.data >= k)
        flag = 1;
    // If the leaf node is encountered, then the path is
    // printed if the size of the path vector is
    // greater than 0
    if (root.left == null && root.right == null)
    {
        if (flag == 1)
        {
            ans = 1;
            System.out.print("(");
            for (int i = 0; i             {
                System.out.print(path.get(i)+ ", ");
            }
            System.out.print(root.data+ "), ");
        }
        return;
    }
    // Append the node to the path vector
    path.add(root.data);
    // Recur left and right subtrees
    findPathUtil(root.left, k, path, flag);
    findPathUtil(root.right, k, path, flag);
    // Backtracking to return the vector
    // and print the path if the flag is 1
    path.remove(path.size()-1);
}
// Function to initialize the variables
// and call the utility function to print
// the paths with maximum values greater than
// or equal to K
static void findPath(Node root, int k)
{
    // Initialize flag
    int flag = 0;
    // ans is used to check empty condition
    ans = 0;
    Vector v = new Vector();
    // Call function that print path
    findPathUtil(root, k, v, flag);
    // If the path doesn't exist
    if (ans == 0)
        System.out.print("-1");
}
// Driver code
public static void main(String [] args)
{
    int K = 25;
    /* Constructing the following tree:
                10
            / \
            5     8
        / \ / \
        29 2 1 98
        /             \    
        20             50
*/
    Node root = newNode(10);
    root.left = newNode(5);
    root.right = newNode(8);
    root.left.left = newNode(29);
    root.left.right = newNode(2);
    root.right.right = newNode(98);
    root.right.left = newNode(1);
    root.right.right.right = newNode(50);
    root.left.left.left = newNode(20);
    findPath(root, K);
}
}
// This code is contributed by PrinciRaj1992

Python 3

# Python3 program to construct string from binary tree
# A Binary Tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
# A recursive function to print the paths
# whose maximum element is greater than
# or equal to K.
def findPathUtil(root: Node, k: int, path: list, flag: int):
    global ans
    if root is None:
        return
    # If the current node value is greater than
    # or equal to k, then all the subtrees
    # following that node will get printed,
    # flag = 1 indicates to print the required path
    if root.data >= k:
        flag = 1
    # If the leaf node is encountered, then the path is
    # printed if the size of the path vector is
    # greater than 0
    if root.left is None and root.right is None:
        if flag:
            ans = 1
            print("(", end = "")
            for i in range(len(path)):
                print(path[i], end = ", ")
            print(root.data, end = "), ")
        return
    # Append the node to the path vector
    path.append(root.data)
    # Recur left and right subtrees
    findPathUtil(root.left, k, path, flag)
    findPathUtil(root.right, k, path, flag)
    # Backtracking to return the vector
    # and print the path if the flag is 1
    path.pop()
# Function to initialize the variables
# and call the utility function to print
# the paths with maximum values greater than
# or equal to K
def findPath(root: Node, k: int):
    global ans
    # Initialize flag
    flag = 0
    # ans is used to check empty condition
    ans = 0
    v = []
    # Call function that print path
    findPathUtil(root, k, v, flag)
    # If the path doesn't exist
    if ans == 0:
        print(-1)
# Driver Code
if __name__ == "__main__":
    ans = 0
    k = 25
    # Constructing the following tree:
    #             10
    #         / \
    #         5     8
    #     / \ / \
    #     29 2 1 98
    #     /             \
    #     20             50
    root = Node(10)
    root.left = Node(5)
    root.right = Node(8)
    root.left.left = Node(29)
    root.left.right = Node(2)
    root.right.right = Node(98)
    root.right.left = Node(1)
    root.right.right.right = Node(50)
    root.left.left.left = Node(20)
    findPath(root, k)
# This code is contributed by
# sanjeev2552

C

// C# program to print paths with maximum
// element in the path greater than K
using System;
using System.Collections.Generic;
class GFG
{
// A Binary Tree node
class Node
{
    public int data;
    public Node left, right;
};
static int ans;
// A utility function to create a new node
static Node newNode(int data)
{
    Node newNode = new Node();
    newNode.data = data;
    newNode.left = newNode.right = null;
    return (newNode);
}
// A recursive function to print the paths
// whose maximum element is greater than
// or equal to K.
static void findPathUtil(Node root, int k,
                        List path,
                        int flag)
{
    if (root == null)
        return;
    // If the current node value is greater than
    // or equal to k, then all the subtrees
    // following that node will get printed,
    // flag = 1 indicates to print the required path
    if (root.data >= k)
        flag = 1;
    // If the leaf node is encountered, then the path is
    // printed if the size of the path vector is
    // greater than 0
    if (root.left == null && root.right == null)
    {
        if (flag == 1)
        {
            ans = 1;
            Console.Write("(");
            for (int i = 0; i             {
                Console.Write(path[i] + ", ");
            }
            Console.Write(root.data + "), ");
        }
        return;
    }
    // Append the node to the path vector
    path.Add(root.data);
    // Recur left and right subtrees
    findPathUtil(root.left, k, path, flag);
    findPathUtil(root.right, k, path, flag);
    // Backtracking to return the vector
    // and print the path if the flag is 1
    path.RemoveAt(path.Count-1);
}
// Function to initialize the variables
// and call the utility function to print
// the paths with maximum values greater than
// or equal to K
static void findPath(Node root, int k)
{
    // Initialize flag
    int flag = 0;
    // ans is used to check empty condition
    ans = 0;
    List v = new List();
    // Call function that print path
    findPathUtil(root, k, v, flag);
    // If the path doesn't exist
    if (ans == 0)
        Console.Write("-1");
}
// Driver code
public static void Main(String [] args)
{
    int K = 25;
    /* Constructing the following tree:
                10
            / \
            5     8
        / \ / \
        29 2 1 98
        /             \    
        20             50
*/
    Node root = newNode(10);
    root.left = newNode(5);
    root.right = newNode(8);
    root.left.left = newNode(29);
    root.left.right = newNode(2);
    root.right.right = newNode(98);
    root.right.left = newNode(1);
    root.right.right.right = newNode(50);
    root.left.left.left = newNode(20);
    findPath(root, K);
}
}
// This code is contributed by Rajput-Ji

java 描述语言


Output: 

(10, 5, 29, 20), (10, 8, 98, 50),

推荐阅读
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 本文介绍了解决二叉树层序创建问题的方法。通过使用队列结构体和二叉树结构体,实现了入队和出队操作,并提供了判断队列是否为空的函数。详细介绍了解决该问题的步骤和流程。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文介绍了机器学习手册中关于日期和时区操作的重要性以及其在实际应用中的作用。文章以一个故事为背景,描述了学童们面对老先生的教导时的反应,以及上官如在这个过程中的表现。同时,文章也提到了顾慎为对上官如的恨意以及他们之间的矛盾源于早年的结局。最后,文章强调了日期和时区操作在机器学习中的重要性,并指出了其在实际应用中的作用和意义。 ... [详细]
  • 浏览器中的异常检测算法及其在深度学习中的应用
    本文介绍了在浏览器中进行异常检测的算法,包括统计学方法和机器学习方法,并探讨了异常检测在深度学习中的应用。异常检测在金融领域的信用卡欺诈、企业安全领域的非法入侵、IT运维中的设备维护时间点预测等方面具有广泛的应用。通过使用TensorFlow.js进行异常检测,可以实现对单变量和多变量异常的检测。统计学方法通过估计数据的分布概率来计算数据点的异常概率,而机器学习方法则通过训练数据来建立异常检测模型。 ... [详细]
  • 本文介绍了使用哈夫曼树实现文件压缩和解压的方法。首先对数据结构课程设计中的代码进行了分析,包括使用时间调用、常量定义和统计文件中各个字符时相关的结构体。然后讨论了哈夫曼树的实现原理和算法。最后介绍了文件压缩和解压的具体步骤,包括字符统计、构建哈夫曼树、生成编码表、编码和解码过程。通过实例演示了文件压缩和解压的效果。本文的内容对于理解哈夫曼树的实现原理和应用具有一定的参考价值。 ... [详细]
  • 实现一个通讯录系统,可添加、删除、修改、查找、显示、清空、排序通讯录信息
    本文介绍了如何实现一个通讯录系统,该系统可以实现添加、删除、修改、查找、显示、清空、排序通讯录信息的功能。通过定义结构体LINK和PEOPLE来存储通讯录信息,使用相关函数来实现各项功能。详细介绍了每个功能的实现方法。 ... [详细]
  • 开源Keras Faster RCNN模型介绍及代码结构解析
    本文介绍了开源Keras Faster RCNN模型的环境需求和代码结构,包括FasterRCNN源码解析、RPN与classifier定义、data_generators.py文件的功能以及损失计算。同时提供了该模型的开源地址和安装所需的库。 ... [详细]
author-avatar
手机用户2702939047
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有