原文:

给定一棵二叉树,用二维打印它。 例:

input : pointer to root of below tree
             1
            /  \
           2    3 
          / \   / \
         4   5  6  7 
output :
                    7
          3
                    6
1
                    5
          2
                    4

我们强烈建议你尽量减少浏览器,先自己试试这个。 如果我们仔细观察这个模式,我们可以注意到以下几点。 1)最右边的节点打印在第一行,最左边的节点打印在最后一行。 2)每个等级的空间计数增加固定的数量。 所以我们进行反向有序遍历(右-根-左)并打印树节点。我们在每一级都以固定的数量增加空间。 下面是实现。

c

// c   program to print binary tree in 2d
#include
using namespace std;
#define count 10
// a binary tree node
class node
{
    public:
    int data;
    node* left, *right;
    /* constructor that allocates a new node with the
    given data and null left and right pointers. */
    node(int data){
        this->data = data;
        this->left = null;
        this->right = null;
    }
};
// function to print binary tree in 2d
// it does reverse inorder traversal
void print2dutil(node *root, int space)
{
    // base case
    if (root == null)
        return;
    // increase distance between levels
    space  = count;
    // process right child first
    print2dutil(root->right, space);
    // print current node after space
    // count
    cout<data<<"\n";
    // process left child
    print2dutil(root->left, space);
}
// wrapper over print2dutil()
void print2d(node *root)
{
    // pass initial space count as 0
    print2dutil(root, 0);
}
// driver code
int main()
{
    node *root = new node(1);
    root->left = new node(2);
    root->right = new node(3);
    root->left->left = new node(4);
    root->left->right = new node(5);
    root->right->left = new node(6);
    root->right->right = new node(7);
    root->left->left->left = new node(8);
    root->left->left->right = new node(9);
    root->left->right->left = new node(10);
    root->left->right->right = new node(11);
    root->right->left->left = new node(12);
    root->right->left->right = new node(13);
    root->right->right->left = new node(14);
    root->right->right->right = new node(15);
    print2d(root);
    return 0;
}
// this code is contributed by rathbhupendra

c

// program to print binary tree in 2d
#include
#include
#define count 10
// a binary tree node
struct node
{
    int data;
    struct node* left, *right;
};
// helper function to allocates a new node
struct node* newnode(int data)
{
    struct node* node = malloc(sizeof(struct node));
    node->data = data;
    node->left = node->right = null;
    return node;
}
// function to print binary tree in 2d
// it does reverse inorder traversal
void print2dutil(struct node *root, int space)
{
    // base case
    if (root == null)
        return;
    // increase distance between levels
    space  = count;
    // process right child first
    print2dutil(root->right, space);
    // print current node after space
    // count
    printf("\n");
    for (int i = count; i < space; i  )
        printf(" ");
    printf("%d\n", root->data);
    // process left child
    print2dutil(root->left, space);
}
// wrapper over print2dutil()
void print2d(struct node *root)
{
   // pass initial space count as 0
   print2dutil(root, 0);
}
// driver program to test above functions
int main()
{
    struct node *root   = newnode(1);
    root->left   = newnode(2);
    root->right  = newnode(3);
    root->left->left  = newnode(4);
    root->left->right = newnode(5);
    root->right->left  = newnode(6);
    root->right->right = newnode(7);
    root->left->left->left  = newnode(8);
    root->left->left->right  = newnode(9);
    root->left->right->left  = newnode(10);
    root->left->right->right  = newnode(11);
    root->right->left->left  = newnode(12);
    root->right->left->right  = newnode(13);
    root->right->right->left  = newnode(14);
    root->right->right->right  = newnode(15);
    print2d(root);
    return 0;
}

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

// java program to print binary tree in 2d
class gfg
{
static final int count = 10;
// a binary tree node
static class node
{
    int data;
    node left, right;
    /* constructor that allocates a new node with the
    given data and null left and right pointers. */
    node(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
// function to print binary tree in 2d
// it does reverse inorder traversal
static void print2dutil(node root, int space)
{
    // base case
    if (root == null)
        return;
    // increase distance between levels
    space  = count;
    // process right child first
    print2dutil(root.right, space);
    // print current node after space
    // count
    system.out.print("\n");
    for (int i = count; i < space; i  )
        system.out.print(" ");
    system.out.print(root.data   "\n");
    // process left child
    print2dutil(root.left, space);
}
// wrapper over print2dutil()
static void print2d(node root)
{
    // pass initial space count as 0
    print2dutil(root, 0);
}
// driver code
public static void main(string args[])
{
    node root = new node(1);
    root.left = new node(2);
    root.right = new node(3);
    root.left.left = new node(4);
    root.left.right = new node(5);
    root.right.left = new node(6);
    root.right.right = new node(7);
    root.left.left.left = new node(8);
    root.left.left.right = new node(9);
    root.left.right.left = new node(10);
    root.left.right.right = new node(11);
    root.right.left.left = new node(12);
    root.right.left.right = new node(13);
    root.right.right.left = new node(14);
    root.right.right.right = new node(15);
    print2d(root);
}
}
// this code is contributed by arnab kundu

python 3

# python3 program to print binary tree in 2d
count = [10]
# 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 print binary tree in 2d
# it does reverse inorder traversal
def print2dutil(root, space) :
    # base case
    if (root == none) :
        return
    # increase distance between levels
    space  = count[0]
    # process right child first
    print2dutil(root.right, space)
    # print current node after space
    # count
    print()
    for i in range(count[0], space):
        print(end = " ")
    print(root.data)
    # process left child
    print2dutil(root.left, space)
# wrapper over print2dutil()
def print2d(root) :
    # space=[0]
    # pass initial space count as 0
    print2dutil(root, 0)
# driver code
if __name__ == '__main__':
    root = newnode(1)
    root.left = newnode(2)
    root.right = newnode(3)
    root.left.left = newnode(4)
    root.left.right = newnode(5)
    root.right.left = newnode(6)
    root.right.right = newnode(7)
    root.left.left.left = newnode(8)
    root.left.left.right = newnode(9)
    root.left.right.left = newnode(10)
    root.left.right.right = newnode(11)
    root.right.left.left = newnode(12)
    root.right.left.right = newnode(13)
    root.right.right.left = newnode(14)
    root.right.right.right = newnode(15)
    print2d(root)
# this code is contributed by
# shubham singh(shubhamsingh10)

c

// c# program to print binary tree in 2d
using system;
class gfg
{
static readonly int count = 10;
// a binary tree node
public class node
{
    public int data;
    public node left, right;
    /* constructor that allocates a new node with the
    given data and null left and right pointers. */
    public node(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
// function to print binary tree in 2d
// it does reverse inorder traversal
static void print2dutil(node root, int space)
{
    // base case
    if (root == null)
        return;
    // increase distance between levels
    space  = count;
    // process right child first
    print2dutil(root.right, space);
    // print current node after space
    // count
    console.write("\n");
    for (int i = count; i < space; i  )
        console.write(" ");
    console.write(root.data   "\n");
    // process left child
    print2dutil(root.left, space);
}
// wrapper over print2dutil()
static void print2d(node root)
{
    // pass initial space count as 0
    print2dutil(root, 0);
}
// driver code
public static void main(string []args)
{
    node root = new node(1);
    root.left = new node(2);
    root.right = new node(3);
    root.left.left = new node(4);
    root.left.right = new node(5);
    root.right.left = new node(6);
    root.right.right = new node(7);
    root.left.left.left = new node(8);
    root.left.left.right = new node(9);
    root.left.right.left = new node(10);
    root.left.right.right = new node(11);
    root.right.left.left = new node(12);
    root.right.left.right = new node(13);
    root.right.right.left = new node(14);
    root.right.right.right = new node(15);
    print2d(root);
}
}
// this code is contributed by princi singh

java 描述语言


输出:

                              15
                    7
                              14
          3
                              13
                    6
                              12
1
                              11
                    5
                              10
          2
                              9
                    4
                              8

使用层级顺序遍历的另一种pg电子试玩链接的解决方案:

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

import java.util.linkedlist;
public class tree1 {
    public static void main(string[] args) {
        tree1.node root = new tree1.node(1);
        tree1.node temp = null;
        temp = new tree1.node(2);
        root.left=temp;
        temp = new tree1.node(3);
        root.right=temp;
        temp = new tree1.node(4);
        root.left.left = temp;
        temp=new tree1.node(5);
        root.left.right =temp;
        temp=new tree1.node(6);
        root.right.left =temp;
        temp=new tree1.node(7);
        root.right.right = temp;
        temp = new tree1.node(8);
        root.left.left.left = temp;
        temp = new tree1.node(9);
        root.left.left.right = temp;
        temp=new tree1.node(10);
        root.left.right.left = temp;
        temp=new tree1.node(11);
        root.left.right.right = temp;
        temp=new tree1.node(12);
        root.right.left.left = temp;
        temp=new tree1.node(13);
        root.right.left.right = temp;
        temp=new tree1.node(14);
        root.right.right.left = temp;
        temp=new tree1.node(15);
        root.right.right.right = temp;
        printbinarytree(root);
    }
public static class node{
    public node(int data){
        this.data = data;
    }
    int data;
    node left;
    node right;
}
    public static void printbinarytree(node root) {
        linkedlist treelevel = new linkedlist();
        treelevel.add(root);
        linkedlist temp = new linkedlist();
        int counter = 0;
        int height = heightoftree(root)-1;
        //system.out.println(height);
        double numberofelements = (math.pow(2 , (height   1)) - 1);
        //system.out.println(numberofelements);
        while (counter <= height) {
            node removed = treelevel.removefirst();
            if (temp.isempty()) {
                printspace(numberofelements / math.pow(2 , counter   1), removed);
            } else {
                printspace(numberofelements / math.pow(2 , counter), removed);
            }
            if (removed == null) {
                temp.add(null);
                temp.add(null);
            } else {
                temp.add(removed.left);
                temp.add(removed.right);
            }
            if (treelevel.isempty()) {
                system.out.println("");
                system.out.println("");
                treelevel = temp;
                temp = new linkedlist<>();
                counter  ;
            }
        }
    }
public static void printspace(double n, node removed){
    for(;n>0;n--) {
            system.out.print("\t");
    }
    if(removed == null){
        system.out.print(" ");
    }
    else {
        system.out.print(removed.data);
    }
}
public static int heightoftree(node root){
    if(root==null){
        return 0;
    }
     return 1  math.max(heightoftree(root.left),heightoftree(root.right));
}
}

output

                                1
                2                                3
        4                5                6                7
    8        9        10        11        12        13        14        15

输出:

本文由阿迪蒂亚·戈尔供稿。如果你喜欢极客博客并想投稿,你也可以写一篇文章并把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如发现任何不正确的地方,请写评论,或者您想分享更多关于上述话题的信息