原文:

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

:如果 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 << p.first << " ";
    }
}
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 m = new sorteddictionary();
    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