原文:
二叉树的顶视图是从顶部查看树时可见的节点集。 给定一棵二叉树,打印它的顶视图。 可以按任何顺序打印输出节点。
如果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;
queueq;
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<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.queue;
import java.util.treemap;
import java.util.linkedlist;
import java.util.map;
import java.util.map.entry;
// 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)
输出:
following are nodes in top view of binary tree
2136
另一种方法:
这种方法不需要队列。 这里我们使用两个变量,一个用于当前节点到根的垂直距离,另一个用于当前节点到根的深度。 我们使用垂直距离进行索引。 如果具有相同垂直距离的一个节点再次出现,我们将检查新节点的深度相对于映射中具有相同垂直距离的当前节点是较低还是较高。 如果新节点的深度较小,则我们将其替换。
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
输出:
following are nodes in top view of binary tree
2 1 3 6
此方法由 贡献。
以上实现的时间复杂度为o(nlogn)
,其中n
是给定二叉树中的节点数,映射中的每个插入操作都需要o(log n)
复杂度。
本文由 rohan 提供。 如果发现任何不正确的地方,或者想分享有关上述主题的更多信息,请写评论。
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处