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

在二叉树顶视图中打印节点|集合2

在二叉树顶视图中打印节点|集合2原文:https://www

在二叉树顶视图中打印节点|集合 2

原文:https://www . geesforgeks . org/print-nodes-in-top-view-of-二叉树-set-2/

二叉树的俯视图是从顶部看树时可见的一组节点。给定一棵二叉树,打印它的顶视图。输出节点要从左到右打印。

:如果 x 是其水平距离上最顶端的节点,则输出中有一个节点 x。节点 x 的左子节点的水平距离等于 x 减 1 的水平距离,右子节点的水平距离是 x 加 1 的水平距离。

Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output: Top view: 4 2 1 3 7
Input:
1
/ \
2 3
\
4
\
5
\
6
Output: Top view: 2 1 3 6

想法是做一些类似垂直顺序遍历的事情。像垂直顺序遍历一样,我们需要将水平距离相同的节点分组在一起。我们进行水平顺序遍历,以便在水平节点上的最顶端节点比它下面水平距离相同的任何其他节点先被访问。一张地图用于将节点的水平距离与节点的数据和节点的垂直距离进行映射。

下面是上述方法的实现:

C++

// C++ Program to print Top View of Binary Tree
// using hashmap and recursion
#include
using namespace std;
// Node structure
struct Node {
    // Data of the node
    int data;
    // Horizontal Distance of the node
    int hd;
    // Reference to left node
    struct Node* left;
    // Reference to right node
    struct Node* right;
};
// Initialising node
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->hd = INT_MAX;
    node->left = NULL;
    node->right = NULL;
    return node;
}
void printTopViewUtil(Node* root, int height,
    int hd, map >& m)
{
    // Base Case
    if (root == NULL)
        return;
    // If the node for particular horizontal distance
    // is not present in the map, add it.
    // For top view, we consider the first element
    // at horizontal distance in level order traversal
    if (m.find(hd) == m.end()) {
        m[hd] = make_pair(root->data, height);
    }
    else{
        pair p = (m.find(hd))->second;
        if (p.second > height) {
            m.erase(hd);
            m[hd] = make_pair(root->data, height);
        }
    }
    // Recur for left and right subtree
    printTopViewUtil(root->left, height + 1, hd - 1, m);
    printTopViewUtil(root->right, height + 1, hd + 1, m);
}
void printTopView(Node* root)
{
    // Map to store horizontal distance,
    // height and node's data
    map > m;
    printTopViewUtil(root, 0, 0, m);
    // Print the node's value stored by printTopViewUtil()
    for (map >::iterator it = m.begin();
                                        it != m.end(); it++) {
        pair p = it->second;
        cout <    }
}
int main()
{
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->right = newNode(4);
    root->left->right->right = newNode(5);
    root->left->right->right->right = newNode(6);
    cout <<"Top View : ";
    printTopView(root);
    return 0;
}

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

// Java Program to print Top View of Binary Tree
// using hashmap and recursion
import java.util.*;
class GFG {
    // Node structure
    static class Node {
        // Data of the node
        int data;
        // Reference to left node
        Node left;
        // Reference to right node
        Node right;
    };
    static class pair {
        int data, height;
        public pair(int data, int height)
        {
            this.data = data;
            this.height = height;
        }
    }
    // Initialising node
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = null;
        node.right = null;
        return node;
    }
    static void printTopViewUtil(Node root, int height,
                                 int hd,
                                 Map m)
    {
        // Base Case
        if (root == null)
            return;
        // If the node for particular horizontal distance
        // is not present in the map, add it.
        // For top view, we consider the first element
        // at horizontal distance in level order traversal
        if (!m.containsKey(hd)) {
            m.put(hd, new pair(root.data, height));
        }
        else {
            pair p = m.get(hd);
            if (p.height >= height) {
                m.put(hd, new pair(root.data, height));
            }
        }
        // Recur for left and right subtree
        printTopViewUtil(root.left, height + 1, hd - 1, m);
        printTopViewUtil(root.right, height + 1, hd + 1, m);
    }
    static void printTopView(Node root)
    {
        // Map to store horizontal distance,
        // height and node's data
        Map m = new TreeMap<>();
        printTopViewUtil(root, 0, 0, m);
        // Print the node's value stored by
        // printTopViewUtil()
        for (Map.Entry it : m.entrySet()) {
            pair p = it.getValue();
            System.out.print(p.data + " ");
        }
    }
    // Driver code
    public static void main(String[] args)
    {
        Node root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.right = newNode(4);
        root.left.right.right = newNode(5);
        root.left.right.right.right = newNode(6);
        System.out.print("Top View : ");
        printTopView(root);
    }
}

Python 3

# Python3 Program to prTop View of
# Binary Tree using hash and recursion
from collections import OrderedDict
# A binary tree node
class newNode:
    # A constructor to create a
    # new Binary tree Node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
        self.hd = 2**32
def printTopViewUtil(root, height, hd, m):
    # Base Case
    if (root == None):
        return
    # If the node for particular horizontal
    # distance is not present in the map, add it.
    # For top view, we consider the first element
    # at horizontal distance in level order traversal
    if hd not in m :
        m[hd] = [root.data, height]
    else:
        p = m[hd]
        if p[1] > height:
            m[hd] = [root.data, height]
    # Recur for left and right subtree
    printTopViewUtil(root.left,
                     height + 1, hd - 1, m)
    printTopViewUtil(root.right,
                     height + 1, hd + 1, m)
def printTopView(root):
    # to store horizontal distance,
    # height and node's data
    m = OrderedDict()
    printTopViewUtil(root, 0, 0, m)
    # Print the node's value stored
    # by printTopViewUtil()
    for i in sorted(list(m)):
        p = m[i]
        print(p[0], end = " ")
# Driver Code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.right = newNode(4)
root.left.right.right = newNode(5)
root.left.right.right.right = newNode(6)
print("Top View : ", end = "")
printTopView(root)
# This code is contributed by SHUBHAMSINGH10

C

// C# program to print Top View of Binary
// Tree using hashmap and recursion
using System;
using System.Collections.Generic;
class GFG{
// Node structure
class Node
{
    // Data of the node
    public int data;
    // Reference to left node
    public Node left;
    // Reference to right node
    public Node right;
};
class pair
{
    public int data, height;
    public pair(int data, int height)
    {
        this.data = data;
        this.height = height;
    }
}
// Initialising node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return node;
}
static void printTopViewUtil(Node root, int height,
                             int hd,
                             SortedDictionary m)
{
    // Base Case
    if (root == null)
        return;
    // If the node for particular horizontal distance
    // is not present in the map, add it.
    // For top view, we consider the first element
    // at horizontal distance in level order traversal
    if (!m.ContainsKey(hd))
    {
        m[hd] = new pair(root.data, height);
    }
    else
    {
        pair p = m[hd];
        if (p.height >= height)
        {
            m[hd] = new pair(root.data, height);
        }
    }
    // Recur for left and right subtree
    printTopViewUtil(root.left, height + 1,
                     hd - 1, m);
    printTopViewUtil(root.right, height + 1,
                     hd + 1, m);
}
static void printTopView(Node root)
{
    // Map to store horizontal distance,
    // height and node's data
    SortedDictionary                     pair> m = new SortedDictionary                                                    pair>();
    printTopViewUtil(root, 0, 0, m);
    // Print the node's value stored by
    // printTopViewUtil()
    foreach(var it in m.Values)
    {
        Console.Write(it.data + " ");
    }
}
// Driver code
public static void Main(string[] args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.right = newNode(4);
    root.left.right.right = newNode(5);
    root.left.right.right.right = newNode(6);
    Console.Write("Top View : ");
    printTopView(root);
}
}
// This code is contributed by rutvik_56

java 描述语言


Output

Top View : 2 1 3 6

推荐阅读
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
  • HashMap的相关问题及其底层数据结构和操作流程
    本文介绍了关于HashMap的相关问题,包括其底层数据结构、JDK1.7和JDK1.8的差异、红黑树的使用、扩容和树化的条件、退化为链表的情况、索引的计算方法、hashcode和hash()方法的作用、数组容量的选择、Put方法的流程以及并发问题下的操作。文章还提到了扩容死链和数据错乱的问题,并探讨了key的设计要求。对于对Java面试中的HashMap问题感兴趣的读者,本文将为您提供一些有用的技术和经验。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • Oracle seg,V$TEMPSEG_USAGE与Oracle排序的关系及使用方法
    本文介绍了Oracle seg,V$TEMPSEG_USAGE与Oracle排序之间的关系,V$TEMPSEG_USAGE是V_$SORT_USAGE的同义词,通过查询dba_objects和dba_synonyms视图可以了解到它们的详细信息。同时,还探讨了V$TEMPSEG_USAGE的使用方法。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • 本文介绍了Java中Hashtable的clear()方法,该方法用于清除和移除指定Hashtable中的所有键。通过示例程序演示了clear()方法的使用。 ... [详细]
  • 重入锁(ReentrantLock)学习及实现原理
    本文介绍了重入锁(ReentrantLock)的学习及实现原理。在学习synchronized的基础上,重入锁提供了更多的灵活性和功能。文章详细介绍了重入锁的特性、使用方法和实现原理,并提供了类图和测试代码供读者参考。重入锁支持重入和公平与非公平两种实现方式,通过对比和分析,读者可以更好地理解和应用重入锁。 ... [详细]
  • 开源Keras Faster RCNN模型介绍及代码结构解析
    本文介绍了开源Keras Faster RCNN模型的环境需求和代码结构,包括FasterRCNN源码解析、RPN与classifier定义、data_generators.py文件的功能以及损失计算。同时提供了该模型的开源地址和安装所需的库。 ... [详细]
  • 如何使用Python从工程图图像中提取底部的方法?
    本文介绍了使用Python从工程图图像中提取底部的方法。首先将输入图片转换为灰度图像,并进行高斯模糊和阈值处理。然后通过填充潜在的轮廓以及使用轮廓逼近和矩形核进行过滤,去除非矩形轮廓。最后通过查找轮廓并使用轮廓近似、宽高比和轮廓区域进行过滤,隔离所需的底部轮廓,并使用Numpy切片提取底部模板部分。 ... [详细]
author-avatar
手机用户2502940425
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有