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

打印二叉树中任意两个节点之间的路径

打印二叉树中任意两个节点之间的路径原文:https://www

打印二叉树中任意两个节点之间的路径

原文:https://www . geesforgeks . org/print-二叉树中任意两个节点之间的路径/

给定由不同节点和一对节点组成的二叉树。任务是找到并打印二叉树中两个给定节点之间的路径。

例如,在上面的二叉树中节点 7 和 4 之间的路径是 7 - > 3 - > 1 - > 4

这个想法是找到从根节点到两个节点的路径,并将它们存储在两个独立的向量或数组中,比如路径 1 和路径 2。
现在,出现了两种不同的情况:


  1. 如果两个节点在根节点的不同子树中。一个在左子树,另一个在右子树。在这种情况下,很明显根节点将位于从节点 1 到节点 2 的路径之间。因此,以相反的顺序打印路径 1,然后打印路径 2。

  2. 如果节点在同一个子树中。要么在左子树,要么在右子树。在这种情况下,您需要观察从根节点到两个节点的路径将有一个交叉点,在此之前,从根节点到两个节点的路径是公共的。找到该交点,并以类似于上述情况的方式从该点打印节点。

以下是上述方法的实现:

C++

// C++ program to print path between any
// two nodes in a Binary Tree
#include
using namespace std;
// structure of a node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* getNode(int data)
{
    struct Node* newNode = new Node;
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
// Function to check if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
bool getPath(Node* root, vector& arr, int x)
{
    // if root is NULL
    // there is no path
    if (!root)
        return false;
    // push the node's value in 'arr'
    arr.push_back(root->data);
    // if it is the required node
    // return true
    if (root->data == x)
        return true;
    // else check whether the required node lies
    // in the left subtree or right subtree of
    // the current node
    if (getPath(root->left, arr, x) || getPath(root->right, arr, x))
        return true;
    // required node does not lie either in the
    // left or right subtree of the current node
    // Thus, remove current node's value from
    // 'arr'and then return false
    arr.pop_back();
    return false;
}
// Function to print the path between
// any two nodes in a binary tree
void printPathBetweenNodes(Node* root, int n1, int n2)
{
    // vector to store the path of
    // first node n1 from root
    vector path1;
    // vector to store the path of
    // second node n2 from root
    vector path2;
    getPath(root, path1, n1);
    getPath(root, path2, n2);
    int intersection = -1;
    // Get intersection point
    int i = 0, j = 0;
    while (i != path1.size() || j != path2.size()) {
        // Keep moving forward until no intersection
        // is found
        if (i == j && path1[i] == path2[j]) {
            i++;
            j++;
        }
        else {
            intersection = j - 1;
            break;
        }
    }
    // Print the required path
    for (int i = path1.size() - 1; i > intersection; i--)
        cout <    for (int i = intersection; i         cout <}
// Driver program
int main()
{
    // binary tree formation
    struct Node* root = getNode(0);
    root->left = getNode(1);
    root->left->left = getNode(3);
    root->left->left->left = getNode(7);
    root->left->right = getNode(4);
    root->left->right->left = getNode(8);
    root->left->right->right = getNode(9);
    root->right = getNode(2);
    root->right->left = getNode(5);
    root->right->right = getNode(6);
    int node1 = 7;
    int node2 = 4;
    printPathBetweenNodes(root, node1, node2);
    return 0;
}

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

// Java program to print path between any
// two nodes in a Binary Tree
import java.util.*;
class Solution
{
// structure of a node of binary tree
static class Node {
    int data;
    Node left, right;
}
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
 static Node getNode(int data)
{
     Node newNode = new Node();
    newNode.data = data;
    newNode.left = newNode.right = null;
    return newNode;
}
// Function to check if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
static boolean getPath(Node root, Vector arr, int x)
{
    // if root is null
    // there is no path
    if (root==null)
        return false;
    // push the node's value in 'arr'
    arr.add(root.data);
    // if it is the required node
    // return true
    if (root.data == x)
        return true;
    // else check whether the required node lies
    // in the left subtree or right subtree of
    // the current node
    if (getPath(root.left, arr, x) || getPath(root.right, arr, x))
        return true;
    // required node does not lie either in the
    // left or right subtree of the current node
    // Thus, remove current node's value from
    // 'arr'and then return false
    arr.remove(arr.size()-1);
    return false;
}
// Function to print the path between
// any two nodes in a binary tree
static void printPathBetweenNodes(Node root, int n1, int n2)
{
    // vector to store the path of
    // first node n1 from root
    Vector path1= new Vector();
    // vector to store the path of
    // second node n2 from root
    Vector path2=new Vector();
    getPath(root, path1, n1);
    getPath(root, path2, n2);
    int intersection = -1;
    // Get intersection point
    int i = 0, j = 0;
    while (i != path1.size() || j != path2.size()) {
        // Keep moving forward until no intersection
        // is found
        if (i == j && path1.get(i) == path2.get(i)) {
            i++;
            j++;
        }
        else {
            intersection = j - 1;
            break;
        }
    }
    // Print the required path
    for ( i = path1.size() - 1; i > intersection; i--)
        System.out.print( path1.get(i) + " ");
    for ( i = intersection; i         System.out.print( path2.get(i) + " ");
}
// Driver program
public static void main(String[] args)
{
    // binary tree formation
     Node root = getNode(0);
    root.left = getNode(1);
    root.left.left = getNode(3);
    root.left.left.left = getNode(7);
    root.left.right = getNode(4);
    root.left.right.left = getNode(8);
    root.left.right.right = getNode(9);
    root.right = getNode(2);
    root.right.left = getNode(5);
    root.right.right = getNode(6);
    int node1 = 7;
    int node2 = 4;
    printPathBetweenNodes(root, node1, node2);
}
}
// This code is contributed by Arnab Kundu

计算机编程语言

# Python3 program to print path between any
# two nodes in a Binary Tree
import sys
import math
# structure of a node of binary tree
class Node:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
# Helper function that allocates a new node with the
#given data and NULL left and right pointers.
def getNode(data):
        return Node(data)
# Function to check if there is a path from root
# to the given node. It also populates
# 'arr' with the given path
def getPath(root, rarr, x):
    # if root is NULL
    # there is no path
    if not root:
        return False
    # push the node's value in 'arr'
    rarr.append(root.data)
    # if it is the required node
    # return true
    if root.data == x:
        return True
    # else check whether the required node lies
    # in the left subtree or right subtree of
    # the current node
    if getPath(root.left, rarr, x) or getPath(root.right, rarr, x):
        return True
    # required node does not lie either in the
    # left or right subtree of the current node
    # Thus, remove current node's value from
    # 'arr'and then return false
    rarr.pop()
    return False
# Function to print the path between
# any two nodes in a binary tree
def printPathBetweenNodes(root, n1, n2):
    # vector to store the path of
    # first node n1 from root
    path1 = []
    # vector to store the path of
    # second node n2 from root
    path2 = []
    getPath(root, path1, n1)
    getPath(root, path2, n2)
    # Get intersection point
    i, j = 0, 0
    intersection=-1
    while(i != len(path1) or j != len(path2)):
        # Keep moving forward until no intersection
        # is found
        if (i == j and path1[i] == path2[j]):
            i += 1
            j += 1
        else:
            intersection = j - 1
            break
    # Print the required path
    for i in range(len(path1) - 1, intersection - 1, -1):
        print("{} ".format(path1[i]), end = "")
    for j in range(intersection + 1, len(path2)):
        print("{} ".format(path2[j]), end = "")
# Driver program
if __name__=='__main__':
    # binary tree formation
    root = getNode(0)
    root.left = getNode(1)
    root.left.left = getNode(3)
    root.left.left.left = getNode(7)
    root.left.right = getNode(4)
    root.left.right.left = getNode(8)
    root.left.right.right = getNode(9)
    root.right = getNode(2)
    root.right.left = getNode(5)
    root.right.right = getNode(6)
    node1=7
    node2=4
    printPathBetweenNodes(root,node1,node2)
# This Code is Contributed By Vikash Kumar 37

C

// C# program to print path between any
// two nodes in a Binary Tree
using System;
using System.Collections.Generic;
class Solution
{
// structure of a node of binary tree
public class Node
{
    public int data;
    public Node left, right;
}
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
static Node getNode(int data)
{
    Node newNode = new Node();
    newNode.data = data;
    newNode.left = newNode.right = null;
    return newNode;
}
// Function to check if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
static Boolean getPath(Node root, List arr, int x)
{
    // if root is null
    // there is no path
    if (root == null)
        return false;
    // push the node's value in 'arr'
    arr.Add(root.data);
    // if it is the required node
    // return true
    if (root.data == x)
        return true;
    // else check whether the required node lies
    // in the left subtree or right subtree of
    // the current node
    if (getPath(root.left, arr, x) || getPath(root.right, arr, x))
        return true;
    // required node does not lie either in the
    // left or right subtree of the current node
    // Thus, remove current node's value from
    // 'arr'and then return false
    arr.RemoveAt(arr.Count-1);
    return false;
}
// Function to print the path between
// any two nodes in a binary tree
static void printPathBetweenNodes(Node root, int n1, int n2)
{
    // vector to store the path of
    // first node n1 from root
    List path1 = new List();
    // vector to store the path of
    // second node n2 from root
    List path2 = new List();
    getPath(root, path1, n1);
    getPath(root, path2, n2);
    int intersection = -1;
    // Get intersection point
    int i = 0, j = 0;
    while (i != path1.Count || j != path2.Count)
    {
        // Keep moving forward until no intersection
        // is found
        if (i == j && path1[i] == path2[i])
        {
            i++;
            j++;
        }
        else
        {
            intersection = j - 1;
            break;
        }
    }
    // Print the required path
    for ( i = path1.Count - 1; i > intersection; i--)
        Console.Write( path1[i] + " ");
    for ( i = intersection; i         Console.Write( path2[i] + " ");
}
// Driver code
public static void Main(String[] args)
{
    // binary tree formation
    Node root = getNode(0);
    root.left = getNode(1);
    root.left.left = getNode(3);
    root.left.left.left = getNode(7);
    root.left.right = getNode(4);
    root.left.right.left = getNode(8);
    root.left.right.right = getNode(9);
    root.right = getNode(2);
    root.right.left = getNode(5);
    root.right.right = getNode(6);
    int node1 = 7;
    int node2 = 4;
    printPathBetweenNodes(root, node1, node2);
}
}
// This code is contributed by Princi Singh

java 描述语言


Output: 

7 3 1 4

推荐阅读
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 本文介绍了[从头学数学]中第101节关于比例的相关问题的研究和修炼过程。主要内容包括[机器小伟]和[工程师阿伟]一起研究比例的相关问题,并给出了一个求比例的函数scale的实现。 ... [详细]
  • LeetCode笔记:剑指Offer 41. 数据流中的中位数(Java、堆、优先队列、知识点)
    本文介绍了LeetCode剑指Offer 41题的解题思路和代码实现,主要涉及了Java中的优先队列和堆排序的知识点。优先队列是Queue接口的实现,可以对其中的元素进行排序,采用小顶堆的方式进行排序。本文还介绍了Java中queue的offer、poll、add、remove、element、peek等方法的区别和用法。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • 李逍遥寻找仙药的迷阵之旅
    本文讲述了少年李逍遥为了救治婶婶的病情,前往仙灵岛寻找仙药的故事。他需要穿越一个由M×N个方格组成的迷阵,有些方格内有怪物,有些方格是安全的。李逍遥需要避开有怪物的方格,并经过最少的方格,找到仙药。在寻找的过程中,他还会遇到神秘人物。本文提供了一个迷阵样例及李逍遥找到仙药的路线。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有