📌  相关文章
📜  在二叉树的顶视图中打印节点

📅  最后修改于: 2021-10-27 16:42:57             🧑  作者: Mango

二叉树的顶视图是从顶部查看树时可见的节点集。给定一个二叉树,打印它的顶视图。输出节点可以按任何顺序打印。

如果 x 是其水平距离的最顶部节点,则节点 x 在输出中。节点x的左孩子的水平距离等于x的水平距离减1,右孩子的水平距离是x的水平距离加1。

1
    /     \
   2       3
  /  \    / \
 4    5  6   7
Top view of the above binary tree is
4 2 1 3 7

        1
      /   \
    2       3
      \   
        4  
          \
            5
             \
               6
Top view of the above binary tree is
2 1 3 6

这个想法是做一些类似于垂直订单遍历的事情。与垂直顺序遍历一样,我们需要将相同水平距离的节点放在一起。我们进行水平顺序遍历,以便在其下方具有相同水平距离的任何其他节点之前访问水平节点的最顶部节点。散列用于检查是否看到给定水平距离处的节点。

C++
// C++ program to print top
// view of binary tree
 
#include 
using namespace std;
 
// Structure of binary tree
struct Node {
    Node* left;
    Node* right;
    int hd;
    int data;
};
 
// function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
 
// function should print the topView of
// the binary tree
void topview(Node* root)
{
    if (root == NULL)
        return;
    queue q;
    map m;
    int hd = 0;
    root->hd = hd;
 
    // push node and horizontal distance to queue
    q.push(root);
 
    cout << "The top view of the tree is : \n";
 
    while (q.size()) {
        hd = root->hd;
 
        // count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        if (m.count(hd) == 0)
            m[hd] = root->data;
        if (root->left) {
            root->left->hd = hd - 1;
            q.push(root->left);
        }
        if (root->right) {
            root->right->hd = hd + 1;
            q.push(root->right);
        }
        q.pop();
        root = q.front();
    }
 
    for (auto i = m.begin(); i != m.end(); i++) {
        cout << i->second << " ";
    }
}
 
// Driver Program to test above functions
int main()
{
    /* Create following Binary Tree
            1
        / \
        2 3
        \
            4
            \
            5
            \
                6*/
    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 << "Following are nodes in top view of Binary "
            "Tree\n";
    topview(root);
    return 0;
}
/* This code is contributed by Niteesh Kumar */


Java
// Java program to print top
// view of binary tree
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.TreeMap;
 
// class to create a node
class Node {
    int data;
    Node left, right;
 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
 
// class of binary tree
class BinaryTree {
    Node root;
 
    public BinaryTree() { root = null; }
 
    // function should print the topView of
    // the binary tree
    private void TopView(Node root)
    {
        class QueueObj {
            Node node;
            int hd;
 
            QueueObj(Node node, int hd)
            {
                this.node = node;
                this.hd = hd;
            }
        }
        Queue q = new LinkedList();
        Map topViewMap
            = new TreeMap();
 
        if (root == null) {
            return;
        }
        else {
            q.add(new QueueObj(root, 0));
        }
 
        System.out.println(
            "The top view of the tree is : ");
 
        // count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        while (!q.isEmpty()) {
            QueueObj tmpNode = q.poll();
            if (!topViewMap.containsKey(tmpNode.hd)) {
                topViewMap.put(tmpNode.hd, tmpNode.node);
            }
 
            if (tmpNode.node.left != null) {
                q.add(new QueueObj(tmpNode.node.left,
                                   tmpNode.hd - 1));
            }
            if (tmpNode.node.right != null) {
                q.add(new QueueObj(tmpNode.node.right,
                                   tmpNode.hd + 1));
            }
        }
        for (Entry entry :
             topViewMap.entrySet()) {
            System.out.print(entry.getValue().data);
        }
    }
 
    // Driver Program to test above functions
    public static void main(String[] args)
    {
        /* Create following Binary Tree
            1
        / \
        2 3
        \
            4
            \
            5
            \
                6*/
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.right = new Node(4);
        tree.root.left.right.right = new Node(5);
        tree.root.left.right.right.right = new Node(6);
        System.out.println(
            "Following are nodes in top view of Binary Tree");
        tree.TopView(tree.root);
    }
}


Python3
# Python3 program to print top
# view of binary tree
 
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
 
 
class newNode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
        self.hd = 0
 
# function should print the topView
# of the binary tree
 
 
def topview(root):
 
    if(root == None):
        return
    q = []
    m = dict()
    hd = 0
    root.hd = hd
 
    # push node and horizontal
    # distance to queue
    q.append(root)
 
    while(len(q)):
        root = q[0]
        hd = root.hd
 
        # count function returns 1 if the
        # container contains an element
        # whose key is equivalent to hd,
        # or returns zero otherwise.
        if hd not in m:
            m[hd] = root.data
        if(root.left):
            root.left.hd = hd - 1
            q.append(root.left)
 
        if(root.right):
            root.right.hd = hd + 1
            q.append(root.right)
 
        q.pop(0)
    for i in sorted(m):
        print(m[i], end="")
 
 
# Driver Code
if __name__ == '__main__':
 
    """ Create following Binary Tree
            1
        / \
        2 3
        \
            4
            \
            5
            \
                6*"""
    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("Following are nodes in top",
          "view of Binary Tree")
    topview(root)
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#
// C# program to print top
// view of binary tree
using System;
using System.Collections;
using System.Collections.Generic;
 
// Class to create a node
class Node {
    public int data;
    public Node left, right;
 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
};
 
class QueueObj {
    public Node node;
    public int hd;
 
    public QueueObj(Node node, int hd)
    {
        this.node = node;
        this.hd = hd;
    }
};
 
// Class of binary tree
class BinaryTree {
 
    Node root;
 
    public BinaryTree() { root = null; }
 
    // function should print the topView of
    // the binary tree
    void TopView(Node root)
    {
        Queue q = new Queue();
        SortedDictionary topViewMap
            = new SortedDictionary();
 
        if (root == null) {
            return;
        }
        else {
            q.Enqueue(new QueueObj(root, 0));
        }
 
        // count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        while (q.Count != 0) {
            QueueObj tmpNode = (QueueObj)q.Dequeue();
 
            if (!topViewMap.ContainsKey(tmpNode.hd)) {
                topViewMap[tmpNode.hd] = tmpNode.node;
            }
 
            if (tmpNode.node.left != null) {
                q.Enqueue(new QueueObj(tmpNode.node.left,
                                       tmpNode.hd - 1));
            }
            if (tmpNode.node.right != null) {
                q.Enqueue(new QueueObj(tmpNode.node.right,
                                       tmpNode.hd + 1));
            }
        }
 
        foreach(var entry in topViewMap.Values)
        {
            Console.Write(entry.data);
        }
    }
 
    // Driver code
    public static void Main(string[] args)
    {
 
        /* Create following Binary Tree
            1
           / \
          2   3
           \
            4
             \
              5
               \
                6*/
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.right = new Node(4);
        tree.root.left.right.right = new Node(5);
        tree.root.left.right.right.right = new Node(6);
 
        Console.WriteLine("Following are nodes "
                          + "in top view of Binary Tree");
 
        tree.TopView(tree.root);
    }
}
 
// This code is contributed by rutvik_56


Javascript


C++
#include 
using namespace std;
 
// Structure of binary tree
struct Node {
    Node* left;
    Node* right;
    int data;
};
 
// function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
 
// function to fill the map
void fillMap(Node* root, int d, int l,
             map >& m)
{
    if (root == NULL)
        return;
 
    if (m.count(d) == 0) {
        m[d] = make_pair(root->data, l);
    }
    else if (m[d].second > l) {
        m[d] = make_pair(root->data, l);
    }
 
    fillMap(root->left, d - 1, l + 1, m);
    fillMap(root->right, d + 1, l + 1, m);
}
 
// function should print the topView of
// the binary tree
void topView(struct Node* root)
{
 
    // map to store the pair of node value and its level
    // with respect to the vertical distance from root.
    map > m;
 
    // fillmap(root,vectical_distance_from_root,level_of_node,map)
    fillMap(root, 0, 0, m);
 
    for (auto it = m.begin(); it != m.end(); it++) {
        cout << it->second.first << " ";
    }
}
// Driver Program to test above functions
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 << "Following are nodes in top view of Binary "
            "Tree\n";
    topView(root);
    return 0;
}
/* This code is contributed by Akash Debnath */


Java
// Java program to print top
// view of binary tree
import java.util.*;
 
class GFG {
 
    // Structure of binary tree
    static class Node {
        Node left;
        Node right;
        int data;
    }
 
    static class pair {
        int first, second;
 
        pair() {}
        pair(int i, int j)
        {
            first = i;
            second = j;
        }
    }
 
    // map to store the pair of node value and
    // its level with respect to the vertical
    // distance from root.
    static TreeMap m = new TreeMap<>();
 
    // function to create a new node
    static Node newNode(int key)
    {
        Node node = new Node();
        node.left = node.right = null;
        node.data = key;
        return node;
    }
 
    // function to fill the map
    static void fillMap(Node root, int d, int l)
    {
        if (root == null)
            return;
 
        if (m.get(d) == null) {
            m.put(d, new pair(root.data, l));
        }
        else if (m.get(d).second > l) {
            m.put(d, new pair(root.data, l));
        }
 
        fillMap(root.left, d - 1, l + 1);
        fillMap(root.right, d + 1, l + 1);
    }
 
    // function should print the topView of
    // the binary tree
    static void topView(Node root)
    {
        fillMap(root, 0, 0);
 
        for (Map.Entry entry :
             m.entrySet()) {
            System.out.print(entry.getValue().first + " ");
        }
    }
 
    // 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.println("Following are nodes in"
                           + " top view of Binary Tree");
        topView(root);
    }
}
 
// This code is contributed by Arnab Kundu


Python3
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
 
 
class newNode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# function to fill the map
 
 
def fillMap(root, d, l, m):
    if(root == None):
        return
 
    if d not in m:
        m[d] = [root.data, l]
    elif(m[d][1] > l):
        m[d] = [root.data, l]
    fillMap(root.left, d - 1, l + 1, m)
    fillMap(root.right, d + 1, l + 1, m)
 
# function should prthe topView of
# the binary tree
 
 
def topView(root):
 
    # map to store the pair of node value and its level
    # with respect to the vertical distance from root.
    m = {}
 
    fillMap(root, 0, 0, m)
    for it in sorted(m.keys()):
        print(m[it][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("Following are nodes in top view of Binary Tree")
topView(root)
 
# This code is contributed by SHUBHAMSINGH10


C#
// C# program to print top
// view of binary tree
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG {
 
    // Structure of binary tree
    class Node {
        public Node left;
        public Node right;
        public int data;
    }
 
    class pair {
        public int first, second;
 
        public pair(int i, int j)
        {
            first = i;
            second = j;
        }
    }
 
    // map to store the pair of node value and
    // its level with respect to the vertical
    // distance from root.
    static SortedDictionary m
        = new SortedDictionary();
 
    // function to create a new node
    static Node newNode(int key)
    {
        Node node = new Node();
        node.left = node.right = null;
        node.data = key;
        return node;
    }
 
    // function to fill the map
    static void fillMap(Node root, int d, int l)
    {
        if (root == null)
            return;
 
        if (!m.ContainsKey(d)) {
            m[d] = new pair(root.data, l);
        }
        else if (m[d].second > l) {
            m[d] = new pair(root.data, l);
        }
 
        fillMap(root.left, d - 1, l + 1);
        fillMap(root.right, d + 1, l + 1);
    }
 
    // function should print the topView of
    // the binary tree
    static void topView(Node root)
    {
        fillMap(root, 0, 0);
 
        foreach(pair entry in m.Values)
        {
            Console.Write(entry.first + " ");
        }
    }
 
    // 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.WriteLine("Following are nodes in"
                          + " top view of Binary Tree");
        topView(root);
    }
}
 
// This code is contributed by pratham76


Javascript


C++14
// C++ Program to print Top View of a binary Tree
 
#include 
#include 
#include 
using namespace std;
 
// class for Tree node
class Node {
public:
    Node *left, *right;
    int data;
    Node() { left = right = 0; }
    Node(int data)
    {
        left = right = 0;
        this->data = data;
    }
};
 
/*
          1
         / \
        2   3
         \
          4
           \
            5
             \
              6
    Top view of the above binary tree is
    2 1 3 6
*/
 
// class for Tree
class Tree {
public:
    Node* root;
    Tree() { root = 0; }
 
    void topView()
    {
        // queue for holding nodes and their horizontal
        // distance from the root node
        queue > q;
 
        // pushing root node with distance 0
        q.push(make_pair(root, 0));
 
        // hd is currect node's horizontal distance from
        // root node l is currect left min horizontal
        // distance (or max in magnitude) so far from the
        // root node r is currect right max horizontal
        // distance so far from the root node
 
        int hd = 0, l = 0, r = 0;
 
        // stack is for holding left node's data because
        // they will appear in reverse order that is why
        // using stack
        stack left;
 
        // vector is for holding right node's data
        vector right;
 
        Node* node;
 
        while (q.size()) {
 
            node = q.front().first;
            hd = q.front().second;
 
            if (hd < l) {
                left.push(node->data);
                l = hd;
            }
            else if (hd > r) {
                right.push_back(node->data);
                r = hd;
            }
 
            if (node->left) {
                q.push(make_pair(node->left, hd - 1));
            }
            if (node->right) {
                q.push(make_pair(node->right, hd + 1));
            }
 
            q.pop();
        }
        // printing the left node's data in reverse order
        while (left.size()) {
            cout << left.top() << " ";
            left.pop();
        }
 
        // then printing the root node's data
        cout << root->data << " ";
 
        // finally printing the right node's data
        for (auto x : right) {
            cout << x << " ";
        }
    }
};
 
// Driver code
int main()
{
    // Tree object
    Tree t;
    t.root = new Node(1);
    t.root->left = new Node(2);
    t.root->right = new Node(3);
    t.root->left->right = new Node(4);
    t.root->left->right->right = new Node(5);
    t.root->left->right->right->right = new Node(6);
    t.topView();
    cout << endl;
    return 0;
}


Python3
# Python program for the above approach
from queue import deque
 
def topView(root):
    dic = {}
 
    # variable which is going to store
    # the minimum positional value.
    mi = float('inf')
 
    if not root:
        return ret
 
    q = deque([(root, 0)])
 
    while q:
        cur = q.popleft()
        if cur[1] not in dic:
            dic[cur[1]] = cur[0].data
            mi = min(mi, cur[1])
        if cur[0].left:
            q.append((cur[0].left, cur[1] - 1))
        if cur[0].right:
            q.append((cur[0].right, cur[1] + 1))
 
    # Starting from the leftmost node and
    # just incrementing it until
    # the rightmost node stored in the dic.
    while mi in dic:
        print(dic[mi], end=' ')
        mi += 1
 
 
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None
 
# Driver Code
if __name__ == '__main__':
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.right = Node(4)
    root.left.right.right = Node(5)
    root.left.right.right.right = Node(6)
    print("Top view of Binary Tree (from left to right) is as follows:")
    topView(root)
    # This code is contributed by Karthikayan Mailsamy.


输出
Following are nodes in top view of Binary Tree
The top view of the tree is : 
2 1 3 6 

另一种方法:
这种方法不需要队列。这里我们使用两个变量,一个是当前节点到根的垂直距离,另一个是当前节点到根的深度。我们使用垂直距离进行索引。如果有相同垂直距离的节点再次出现,我们检查新节点的深度相对于地图中具有相同垂直距离的当前节点是低还是高。如果新节点的深度较低,那么我们替换它。

C++

#include 
using namespace std;
 
// Structure of binary tree
struct Node {
    Node* left;
    Node* right;
    int data;
};
 
// function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
 
// function to fill the map
void fillMap(Node* root, int d, int l,
             map >& m)
{
    if (root == NULL)
        return;
 
    if (m.count(d) == 0) {
        m[d] = make_pair(root->data, l);
    }
    else if (m[d].second > l) {
        m[d] = make_pair(root->data, l);
    }
 
    fillMap(root->left, d - 1, l + 1, m);
    fillMap(root->right, d + 1, l + 1, m);
}
 
// function should print the topView of
// the binary tree
void topView(struct Node* root)
{
 
    // map to store the pair of node value and its level
    // with respect to the vertical distance from root.
    map > m;
 
    // fillmap(root,vectical_distance_from_root,level_of_node,map)
    fillMap(root, 0, 0, m);
 
    for (auto it = m.begin(); it != m.end(); it++) {
        cout << it->second.first << " ";
    }
}
// Driver Program to test above functions
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 << "Following are nodes in top view of Binary "
            "Tree\n";
    topView(root);
    return 0;
}
/* This code is contributed by Akash Debnath */

Java

// Java program to print top
// view of binary tree
import java.util.*;
 
class GFG {
 
    // Structure of binary tree
    static class Node {
        Node left;
        Node right;
        int data;
    }
 
    static class pair {
        int first, second;
 
        pair() {}
        pair(int i, int j)
        {
            first = i;
            second = j;
        }
    }
 
    // map to store the pair of node value and
    // its level with respect to the vertical
    // distance from root.
    static TreeMap m = new TreeMap<>();
 
    // function to create a new node
    static Node newNode(int key)
    {
        Node node = new Node();
        node.left = node.right = null;
        node.data = key;
        return node;
    }
 
    // function to fill the map
    static void fillMap(Node root, int d, int l)
    {
        if (root == null)
            return;
 
        if (m.get(d) == null) {
            m.put(d, new pair(root.data, l));
        }
        else if (m.get(d).second > l) {
            m.put(d, new pair(root.data, l));
        }
 
        fillMap(root.left, d - 1, l + 1);
        fillMap(root.right, d + 1, l + 1);
    }
 
    // function should print the topView of
    // the binary tree
    static void topView(Node root)
    {
        fillMap(root, 0, 0);
 
        for (Map.Entry entry :
             m.entrySet()) {
            System.out.print(entry.getValue().first + " ");
        }
    }
 
    // 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.println("Following are nodes in"
                           + " top view of Binary Tree");
        topView(root);
    }
}
 
// This code is contributed by Arnab Kundu

蟒蛇3

# Binary Tree Node
""" utility that allocates a newNode
with the given key """
 
 
class newNode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# function to fill the map
 
 
def fillMap(root, d, l, m):
    if(root == None):
        return
 
    if d not in m:
        m[d] = [root.data, l]
    elif(m[d][1] > l):
        m[d] = [root.data, l]
    fillMap(root.left, d - 1, l + 1, m)
    fillMap(root.right, d + 1, l + 1, m)
 
# function should prthe topView of
# the binary tree
 
 
def topView(root):
 
    # map to store the pair of node value and its level
    # with respect to the vertical distance from root.
    m = {}
 
    fillMap(root, 0, 0, m)
    for it in sorted(m.keys()):
        print(m[it][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("Following are nodes in top view of Binary Tree")
topView(root)
 
# This code is contributed by SHUBHAMSINGH10

C#

// C# program to print top
// view of binary tree
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG {
 
    // Structure of binary tree
    class Node {
        public Node left;
        public Node right;
        public int data;
    }
 
    class pair {
        public int first, second;
 
        public pair(int i, int j)
        {
            first = i;
            second = j;
        }
    }
 
    // map to store the pair of node value and
    // its level with respect to the vertical
    // distance from root.
    static SortedDictionary m
        = new SortedDictionary();
 
    // function to create a new node
    static Node newNode(int key)
    {
        Node node = new Node();
        node.left = node.right = null;
        node.data = key;
        return node;
    }
 
    // function to fill the map
    static void fillMap(Node root, int d, int l)
    {
        if (root == null)
            return;
 
        if (!m.ContainsKey(d)) {
            m[d] = new pair(root.data, l);
        }
        else if (m[d].second > l) {
            m[d] = new pair(root.data, l);
        }
 
        fillMap(root.left, d - 1, l + 1);
        fillMap(root.right, d + 1, l + 1);
    }
 
    // function should print the topView of
    // the binary tree
    static void topView(Node root)
    {
        fillMap(root, 0, 0);
 
        foreach(pair entry in m.Values)
        {
            Console.Write(entry.first + " ");
        }
    }
 
    // 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.WriteLine("Following are nodes in"
                          + " top view of Binary Tree");
        topView(root);
    }
}
 
// This code is contributed by pratham76

Javascript


输出
Following are nodes in top view of Binary Tree
2 1 3 6 

这种方法由 Akash Debnath 贡献
https://www.youtube.com/watch?v=KXfok9IiVHQ上述实现的时间复杂度为 O(nlogn),其中 n 是给定二叉树中的节点数,Map 中的每个插入操作都需要 O(log 2 n) 复杂度。

另一种方法:

  1. 这种方法是基于层序遍历的。我们将记录当前距离根的左、右水平距离的最大值。
  2. 如果我们发现更短的距离(或更大的幅度),那么 max left so far distance 然后更新它并将此节点上的数据推送到堆栈(使用堆栈是因为在级别顺序遍历中,左节点将以相反的顺序出现),或者,如果我们发现更大的距离,则 max right so far distance 然后更新它并将此节点上的数据推送到向量。
  3. 在这种方法中,不使用地图。

C++14

// C++ Program to print Top View of a binary Tree
 
#include 
#include 
#include 
using namespace std;
 
// class for Tree node
class Node {
public:
    Node *left, *right;
    int data;
    Node() { left = right = 0; }
    Node(int data)
    {
        left = right = 0;
        this->data = data;
    }
};
 
/*
          1
         / \
        2   3
         \
          4
           \
            5
             \
              6
    Top view of the above binary tree is
    2 1 3 6
*/
 
// class for Tree
class Tree {
public:
    Node* root;
    Tree() { root = 0; }
 
    void topView()
    {
        // queue for holding nodes and their horizontal
        // distance from the root node
        queue > q;
 
        // pushing root node with distance 0
        q.push(make_pair(root, 0));
 
        // hd is currect node's horizontal distance from
        // root node l is currect left min horizontal
        // distance (or max in magnitude) so far from the
        // root node r is currect right max horizontal
        // distance so far from the root node
 
        int hd = 0, l = 0, r = 0;
 
        // stack is for holding left node's data because
        // they will appear in reverse order that is why
        // using stack
        stack left;
 
        // vector is for holding right node's data
        vector right;
 
        Node* node;
 
        while (q.size()) {
 
            node = q.front().first;
            hd = q.front().second;
 
            if (hd < l) {
                left.push(node->data);
                l = hd;
            }
            else if (hd > r) {
                right.push_back(node->data);
                r = hd;
            }
 
            if (node->left) {
                q.push(make_pair(node->left, hd - 1));
            }
            if (node->right) {
                q.push(make_pair(node->right, hd + 1));
            }
 
            q.pop();
        }
        // printing the left node's data in reverse order
        while (left.size()) {
            cout << left.top() << " ";
            left.pop();
        }
 
        // then printing the root node's data
        cout << root->data << " ";
 
        // finally printing the right node's data
        for (auto x : right) {
            cout << x << " ";
        }
    }
};
 
// Driver code
int main()
{
    // Tree object
    Tree t;
    t.root = new Node(1);
    t.root->left = new Node(2);
    t.root->right = new Node(3);
    t.root->left->right = new Node(4);
    t.root->left->right->right = new Node(5);
    t.root->left->right->right->right = new Node(6);
    t.topView();
    cout << endl;
    return 0;
}
输出
2 1 3 6 

这种方法是由Surat Prakash Maurya贡献的。

由于没有使用 Map,上述实现的时间复杂度为 O(n),其中 n 是给定二叉树中的节点数。

另一种方法:

这种方法建立在上面讨论的带有散列映射方法的级别顺序遍历之上。我只是做了一个简单的 tweek 来降低算法的整体时间复杂度。

由于涉及排序,下面实现的时间复杂度为 O(N),其中 N 是二叉树中的节点数,空间复杂度在最坏情况下为 O((二叉树的深度 * 2) – 1)。

蟒蛇3

# Python program for the above approach
from queue import deque
 
def topView(root):
    dic = {}
 
    # variable which is going to store
    # the minimum positional value.
    mi = float('inf')
 
    if not root:
        return ret
 
    q = deque([(root, 0)])
 
    while q:
        cur = q.popleft()
        if cur[1] not in dic:
            dic[cur[1]] = cur[0].data
            mi = min(mi, cur[1])
        if cur[0].left:
            q.append((cur[0].left, cur[1] - 1))
        if cur[0].right:
            q.append((cur[0].right, cur[1] + 1))
 
    # Starting from the leftmost node and
    # just incrementing it until
    # the rightmost node stored in the dic.
    while mi in dic:
        print(dic[mi], end=' ')
        mi += 1
 
 
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None
 
# Driver Code
if __name__ == '__main__':
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.right = Node(4)
    root.left.right.right = Node(5)
    root.left.right.right.right = Node(6)
    print("Top view of Binary Tree (from left to right) is as follows:")
    topView(root)
    # This code is contributed by Karthikayan Mailsamy.
输出
Top view of Binary Tree (from left to right) is as follows:
2 1 3 6 

时间复杂度: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程