热门标签 | 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

推荐阅读
  • 本文介绍了使用哈夫曼树实现文件压缩和解压的方法。首先对数据结构课程设计中的代码进行了分析,包括使用时间调用、常量定义和统计文件中各个字符时相关的结构体。然后讨论了哈夫曼树的实现原理和算法。最后介绍了文件压缩和解压的具体步骤,包括字符统计、构建哈夫曼树、生成编码表、编码和解码过程。通过实例演示了文件压缩和解压的效果。本文的内容对于理解哈夫曼树的实现原理和应用具有一定的参考价值。 ... [详细]
  • 阿里Treebased Deep Match(TDM) 学习笔记及技术发展回顾
    本文介绍了阿里Treebased Deep Match(TDM)的学习笔记,同时回顾了工业界技术发展的几代演进。从基于统计的启发式规则方法到基于内积模型的向量检索方法,再到引入复杂深度学习模型的下一代匹配技术。文章详细解释了基于统计的启发式规则方法和基于内积模型的向量检索方法的原理和应用,并介绍了TDM的背景和优势。最后,文章提到了向量距离和基于向量聚类的索引结构对于加速匹配效率的作用。本文对于理解TDM的学习过程和了解匹配技术的发展具有重要意义。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 李逍遥寻找仙药的迷阵之旅
    本文讲述了少年李逍遥为了救治婶婶的病情,前往仙灵岛寻找仙药的故事。他需要穿越一个由M×N个方格组成的迷阵,有些方格内有怪物,有些方格是安全的。李逍遥需要避开有怪物的方格,并经过最少的方格,找到仙药。在寻找的过程中,他还会遇到神秘人物。本文提供了一个迷阵样例及李逍遥找到仙药的路线。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文介绍了Codeforces Round #321 (Div. 2)比赛中的问题Kefa and Dishes,通过状压和spfa算法解决了这个问题。给定一个有向图,求在不超过m步的情况下,能获得的最大权值和。点不能重复走。文章详细介绍了问题的题意、解题思路和代码实现。 ... [详细]
  • STL迭代器的种类及其功能介绍
    本文介绍了标准模板库(STL)定义的五种迭代器的种类和功能。通过图表展示了这几种迭代器之间的关系,并详细描述了各个迭代器的功能和使用方法。其中,输入迭代器用于从容器中读取元素,输出迭代器用于向容器中写入元素,正向迭代器是输入迭代器和输出迭代器的组合。本文的目的是帮助读者更好地理解STL迭代器的使用方法和特点。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • 本文介绍了解决二叉树层序创建问题的方法。通过使用队列结构体和二叉树结构体,实现了入队和出队操作,并提供了判断队列是否为空的函数。详细介绍了解决该问题的步骤和流程。 ... [详细]
  • Go语言实现堆排序的详细教程
    本文主要介绍了Go语言实现堆排序的详细教程,包括大根堆的定义和完全二叉树的概念。通过图解和算法描述,详细介绍了堆排序的实现过程。堆排序是一种效率很高的排序算法,时间复杂度为O(nlgn)。阅读本文大约需要15分钟。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • HashMap的相关问题及其底层数据结构和操作流程
    本文介绍了关于HashMap的相关问题,包括其底层数据结构、JDK1.7和JDK1.8的差异、红黑树的使用、扩容和树化的条件、退化为链表的情况、索引的计算方法、hashcode和hash()方法的作用、数组容量的选择、Put方法的流程以及并发问题下的操作。文章还提到了扩容死链和数据错乱的问题,并探讨了key的设计要求。对于对Java面试中的HashMap问题感兴趣的读者,本文将为您提供一些有用的技术和经验。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
  • 本文介绍了一道经典的状态压缩题目——关灯问题2,并提供了解决该问题的算法思路。通过使用二进制表示灯的状态,并枚举所有可能的状态,可以求解出最少按按钮的次数,从而将所有灯关掉。本文还对状压和位运算进行了解释,并指出了该方法的适用性和局限性。 ... [详细]
  • 如何使用Python从工程图图像中提取底部的方法?
    本文介绍了使用Python从工程图图像中提取底部的方法。首先将输入图片转换为灰度图像,并进行高斯模糊和阈值处理。然后通过填充潜在的轮廓以及使用轮廓逼近和矩形核进行过滤,去除非矩形轮廓。最后通过查找轮廓并使用轮廓近似、宽高比和轮廓区域进行过滤,隔离所需的底部轮廓,并使用Numpy切片提取底部模板部分。 ... [详细]
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社区 版权所有