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

当二叉树的节点成为叶节点时打印它们

当二叉树的节点成为叶节点时打印它们原文:https://www

当二叉树的节点成为叶节点时打印它们

原文:https://www . geesforgeks . org/print-二叉树的节点成为叶子节点/

给定一棵二叉树。首先打印所有的叶节点,然后从树中移除所有的叶节点,现在打印所有新形成的叶节点,并一直这样做,直到所有的节点都从树中移除。
:

Input :
8
/ \
3 10
/ \ / \
1 6 14 4
/ \
7 13
Output :
4 6 7 13 14
1 10
3
8

来源 : Flipkart 校园招聘
途径:思路是进行简单的 dfs,根据以下条件给每个节点分配不同的值:


  1. 最初将值为 0 的所有节点赋值。

  2. 现在,给所有节点赋值为(两个子节点的最大值)+1

DFS 之前的树:临时值零被分配给所有节点。

before dfs

DFS 后的树:节点赋值为(两个子节点的最大值)+1

after dfs

现在,您可以在上面的树中看到,在将所有值分配给每个节点后,任务现在减少到根据分配给它们的节点值的升序来打印树。
以下是上述方法的实施:

C++

// C++ program to print the nodes of binary
// tree as they become the leaf node
#include
using namespace std;
// Binary tree node
struct Node {
    int data;
    int order;
    struct Node* left;
    struct Node* right;
};
// Utility function to allocate a new node
struct Node* newNode(int data, int order)
{
    struct Node* node = new Node;
    node->data = data;
    node->order = order;
    node->left = NULL;
    node->right = NULL;
    return (node);
}
// Function for postorder traversal of tree and
// assigning values to nodes
void Postorder(struct Node* node, vector >& v)
{
    if (node == NULL)
        return;
    /* first recur on left child */
    Postorder(node->left, v);
    /* now recur on right child */
    Postorder(node->right, v);
    // If current node is leaf node, it's order will be 1
    if (node->right == NULL && node->left == NULL) {
        node->order = 1;
        // make pair of assigned value and tree value
        v.push_back(make_pair(node->order, node->data));
    }
    else {
        // otherwise, the order will be:
        // max(left_child_order, right_child_order) + 1
        node->order = max((node->left)->order, (node->right)->order) + 1;
        // make pair of assigned value and tree value
        v.push_back(make_pair(node->order, node->data));
    }
}
// Function to print leaf nodes in
// the given order
void printLeafNodes(int n, vector >& v)
{
    // Sort the vector in increasing order of
    // assigned node values
    sort(v.begin(), v.end());
    for (int i = 0; i         if (v[i].first == v[i + 1].first)
            cout <        else
            cout <    }
}
// Driver Code
int main()
{
    struct Node* root = newNode(8, 0);
    root->left = newNode(3, 0);
    root->right = newNode(10, 0);
    root->left->left = newNode(1, 0);
    root->left->right = newNode(6, 0);
    root->right->left = newNode(14, 0);
    root->right->right = newNode(4, 0);
    root->left->left->left = newNode(7, 0);
    root->left->left->right = newNode(13, 0);
    int n = 9;
    vector > v;
    Postorder(root, v);
    printLeafNodes(n, v);
    return 0;
}

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

// Java program to print the nodes of binary
// tree as they become the leaf node
import java.util.*;
class GFG
{
// Binary tree node
static class Node
{
    int data;
    int order;
    Node left;
    Node right;
};
static class Pair
{
    int first,second;
    Pair(int a,int b)
    {
        first = a;
        secOnd= b;
    }
}
// Utility function to allocate a new node
static Node newNode(int data, int order)
{
    Node node = new Node();
    node.data = data;
    node.order = order;
    node.left = null;
    node.right = null;
    return (node);
}
static Vector v = new Vector();
// Function for postorder traversal of tree and
// assigning values to nodes
static void Postorder(Node node)
{
    if (node == null)
        return;
    /* first recur on left child */
    Postorder(node.left);
    /* now recur on right child */
    Postorder(node.right);
    // If current node is leaf node, it's order will be 1
    if (node.right == null && node.left == null)
    {
        node.order = 1;
        // make pair of assigned value and tree value
        v.add(new Pair(node.order, node.data));
    }
    else
    {
        // otherwise, the order will be:
        // max(left_child_order, right_child_order) + 1
        node.order = Math.max((node.left).order, (node.right).order) + 1;
        // make pair of assigned value and tree value
        v.add(new Pair(node.order, node.data));
    }
}
static class Sort implements Comparator
{
    // Used for sorting in ascending order of
    // roll number
    public int compare(Pair a, Pair b)
    {
        if(a.first != b.first)
        return (a.first - b.first);
        else
        return (a.second-b.second);
    }
}
// Function to print leaf nodes in
// the given order
static void printLeafNodes(int n)
{
    // Sort the vector in increasing order of
    // assigned node values
    Collections.sort(v,new Sort());
    for (int i = 0; i     {
        if (i != v.size()-1 && v.get(i).first == v.get(i + 1).first)
            System.out.print( v.get(i).second + " ");
        else
            System.out.print( v.get(i).second + "\n");
    }
}
// Driver Code
public static void main(String args[])
{
    Node root = newNode(8, 0);
    root.left = newNode(3, 0);
    root.right = newNode(10, 0);
    root.left.left = newNode(1, 0);
    root.left.right = newNode(6, 0);
    root.right.left = newNode(14, 0);
    root.right.right = newNode(4, 0);
    root.left.left.left = newNode(7, 0);
    root.left.left.right = newNode(13, 0);
    int n = 9;
    Postorder(root);
    printLeafNodes(n);
}
}
// This code is contributed by Arnab Kundu

Python 3

# Python3 program to print the nodes of binary
# tree as they become the leaf node
# Binary tree node
class newNode:
    def __init__(self, data,order):
        self.data = data
        self.order=order
        self.left = None
        self.right = None
# Function for postorder traversal of tree and
# assigning values to nodes
def Postorder(node,v):
    if (node == None):
        return
    """ first recur on left child """
    Postorder(node.left, v)
    """ now recur on right child """
    Postorder(node.right, v)
    # If current node is leaf node,
    # it's order will be 1
    if (node.right == None and
        node.left == None):
        node.order = 1
        # make pair of assigned value and tree value
        v[0].append([node.order, node.data])
    else:
        # otherwise, the order will be:
        # max(left_child_order, right_child_order) + 1
        node.order = max((node.left).order,
                         (node.right).order) + 1
        # make pair of assigned value and tree value
        v[0].append([node.order, node.data])
# Function to print leaf nodes in
# the given order
def printLeafNodes(n, v):
    # Sort the vector in increasing order of
    # assigned node values
    v=sorted(v[0])
    for i in range(n - 1):
        if (v[i][0]== v[i + 1][0]):
            print(v[i][1], end = " ")
        else:
            print(v[i][1])
    if (v[-1][0]== v[-2][0]):
            print(v[-1][1], end = " ")
    else:
        print(v[-1][1])
# Driver Code
root = newNode(8, 0)
root.left = newNode(3, 0)
root.right = newNode(10, 0)
root.left.left = newNode(1, 0)
root.left.right = newNode(6, 0)
root.right.left = newNode(14, 0)
root.right.right = newNode(4, 0)
root.left.left.left = newNode(7, 0)
root.left.left.right = newNode(13, 0)
n = 9
v = [[] for i in range(1)]
Postorder(root, v)
printLeafNodes(n, v)
# This code is contributed by SHUBHAMSINGH10

C

// C# program to print the nodes of binary
// tree as they become the leaf node
using System;
using System.Collections.Generic;
class GFG
{
// Binary tree node
public class Node
{
    public int data;
    public int order;
    public Node left;
    public Node right;
};
public class Pair
{
    public int first,second;
    public Pair(int a,int b)
    {
        first = a;
        secOnd= b;
    }
}
// Utility function to allocate a new node
static Node newNode(int data, int order)
{
    Node node = new Node();
    node.data = data;
    node.order = order;
    node.left = null;
    node.right = null;
    return (node);
}
static List v = new List();
// Function for postorder traversal of
// tree and assigning values to nodes
static void Postorder(Node node)
{
    if (node == null)
        return;
    /* first recur on left child */
    Postorder(node.left);
    /* now recur on right child */
    Postorder(node.right);
    // If current node is leaf node,
    // it's order will be 1
    if (node.right == null &&
        node.left == null)
    {
        node.order = 1;
        // make pair of assigned value
        // and tree value
        v.Add(new Pair(node.order, node.data));
    }
    else
    {
        // otherwise, the order will be:
        // Max(left_child_order,
        //     right_child_order) + 1
        node.order = Math.Max((node.left).order,
                              (node.right).order) + 1;
        // make pair of assigned value
        // and tree value
        v.Add(new Pair(node.order, node.data));
    }
}
// Used for sorting in ascending order
// of roll number
public static int compare(Pair a, Pair b)
{
    if(a.first != b.first)
        return (a.first - b.first);
    else
        return (a.second - b.second);
}
// Function to print leaf nodes in
// the given order
static void printLeafNodes(int n)
{
    // Sort the List in increasing order
    // of assigned node values
    v.Sort(compare);
    for (int i = 0; i     {
        if (i != v.Count - 1 &&
            v[i].first == v[i + 1].first)
            Console.Write(v[i].second + " ");
        else
            Console.Write(v[i].second + "\n");
    }
}
// Driver Code
public static void Main(String[] args)
{
    Node root = newNode(8, 0);
    root.left = newNode(3, 0);
    root.right = newNode(10, 0);
    root.left.left = newNode(1, 0);
    root.left.right = newNode(6, 0);
    root.right.left = newNode(14, 0);
    root.right.right = newNode(4, 0);
    root.left.left.left = newNode(7, 0);
    root.left.left.right = newNode(13, 0);
    int n = 9;
    Postorder(root);
    printLeafNodes(n);
}
}
// This code is contributed
// by Arnab Kundu

java 描述语言


Output: 

4 6 7 13 14
1 10
3
8

时间复杂度 : O(nlogn)
辅助空间 : O(n),其中 n 是给定二叉树中的节点数。


推荐阅读
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • javascript  – 概述在Firefox上无法正常工作
    我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 使用nodejs爬取b站番剧数据,计算最佳追番推荐
    本文介绍了如何使用nodejs爬取b站番剧数据,并通过计算得出最佳追番推荐。通过调用相关接口获取番剧数据和评分数据,以及使用相应的算法进行计算。该方法可以帮助用户找到适合自己的番剧进行观看。 ... [详细]
  • 无损压缩算法专题——LZSS算法实现
    本文介绍了基于无损压缩算法专题的LZSS算法实现。通过Python和C两种语言的代码实现了对任意文件的压缩和解压功能。详细介绍了LZSS算法的原理和实现过程,以及代码中的注释。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 本文介绍了机器学习手册中关于日期和时区操作的重要性以及其在实际应用中的作用。文章以一个故事为背景,描述了学童们面对老先生的教导时的反应,以及上官如在这个过程中的表现。同时,文章也提到了顾慎为对上官如的恨意以及他们之间的矛盾源于早年的结局。最后,文章强调了日期和时区操作在机器学习中的重要性,并指出了其在实际应用中的作用和意义。 ... [详细]
  • 李逍遥寻找仙药的迷阵之旅
    本文讲述了少年李逍遥为了救治婶婶的病情,前往仙灵岛寻找仙药的故事。他需要穿越一个由M×N个方格组成的迷阵,有些方格内有怪物,有些方格是安全的。李逍遥需要避开有怪物的方格,并经过最少的方格,找到仙药。在寻找的过程中,他还会遇到神秘人物。本文提供了一个迷阵样例及李逍遥找到仙药的路线。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 配置IPv4静态路由实现企业网内不同网段用户互访
    本文介绍了通过配置IPv4静态路由实现企业网内不同网段用户互访的方法。首先需要配置接口的链路层协议参数和IP地址,使相邻节点网络层可达。然后按照静态路由组网图的操作步骤,配置静态路由。这样任意两台主机之间都能够互通。 ... [详细]
author-avatar
拍友2602911553
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有