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

求节点到根的距离的迭代程序

求节点到根的距离的迭代程序原文:https://www.ge

求节点到根的距离的迭代程序

原文:https://www . geeksforgeeks . org/迭代程序查找根节点距离/

给定二叉树的根和其中的一个键 x,求给定键到根节点的距离。距离是指两个节点之间的边数。

示例:

Input : x = 45,
5 is Root of below tree
5
/ \
10 15
/ \ / \
20 25 30 35
\
45
Output : Distance = 3
There are three edges on path
from root to 45.
For more understanding of question,
in above tree distance of 35 is two
and distance of 10 is 1.

相关问题 : 求节点距根距离的递归程序。
迭代方法:


  • 使用级别顺序遍历使用队列迭代遍历树。

  • 保留一个变量电平计数来保持当前电平的轨迹。

  • 为此,每次移动到下一个级别时,在将空节点推入队列时,也会增加变量 levelCount 的值,以便存储当前的级别号。

  • 遍历树时,检查当前级别是否有任何节点与给定的键匹配。

  • 如果是,则返回级别计数。

下面是上述方法的实现:

C++

// C++ program to find distance of a given
// node from root.
#include
using namespace std;
// A Binary Tree Node
struct Node {
    int data;
    Node *left, *right;
};
// A utility function to create a new Binary
// Tree Node
Node* newNode(int item)
{
    Node* temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
/* Function to find distance of a node from root
*  root : root of the Tree
*  key : data whose distance to be calculated
*/
int findDistance(Node* root, int key)
{
    // base case
    if (root == NULL) {
        return -1;
    }
    // If the key is present at root,
    // distance is zero
    if (root->data == key)
        return 0;
    // Iterating through tree using BFS
    queue q;
    // pushing root to the queue
    q.push(root);
    // pushing marker to the queue
    q.push(NULL);
    // Variable to store count of level
    int levelCount = 0;
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        // if node is marker, push marker to queue
        // else, push left and right (if exists)
        if (temp == NULL && !q.empty()) {
            q.push(NULL);
            // Increment levelCount, while moving
            // to new level
            levelCount++;
        }
        else if (temp != NULL) {
            // If node at current level is Key,
            // return levelCount
            if (temp->data == key)
                return levelCount;
            if (temp->left)
                q.push(temp->left);
            if (temp->right)
                q.push(temp->right);
        }
    }
    // If key is not found
    return -1;
}
// Driver Code
int main()
{
    Node* root = newNode(5);
    root->left = newNode(10);
    root->right = newNode(15);
    root->left->left = newNode(20);
    root->left->right = newNode(25);
    root->left->right->right = newNode(45);
    root->right->left = newNode(30);
    root->right->right = newNode(35);
    cout <    return 0;
}

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

// Java program to find distance of a given
// node from root.
import java.util.*;
class GFG
{
// A Binary Tree Node
static class Node
{
    int data;
    Node left, right;
};
// A utility function to create a new Binary
// Tree Node
static Node newNode(int item)
{
    Node temp = new Node();
    temp.data = item;
    temp.left = temp.right = null;
    return temp;
}
/* Function to find distance of a node from root
* root : root of the Tree
* key : data whose distance to be calculated
*/
static int findDistance(Node root, int key)
{
    // base case
    if (root == null)
    {
        return -1;
    }
    // If the key is present at root,
    // distance is zero
    if (root.data == key)
        return 0;
    // Iterating through tree using BFS
    Queue q = new LinkedList();
    // adding root to the queue
    q.add(root);
    // adding marker to the queue
    q.add(null);
    // Variable to store count of level
    int levelCount = 0;
    while (!q.isEmpty())
    {
        Node temp = q.peek();
        q.remove();
        // if node is marker, push marker to queue
        // else, push left and right (if exists)
        if (temp == null && !q.isEmpty())
        {
            q.add(null);
            // Increment levelCount, while moving
            // to new level
            levelCount++;
        }
        else if (temp != null)
        {
            // If node at current level is Key,
            // return levelCount
            if (temp.data == key)
                return levelCount;
            if (temp.left != null)
                q.add(temp.left);
            if (temp.right != null)
                q.add(temp.right);
        }
    }
    // If key is not found
    return -1;
}
// Driver Code
public static void main(String[] args)
{
    Node root = newNode(5);
    root.left = newNode(10);
    root.right = newNode(15);
    root.left.left = newNode(20);
    root.left.right = newNode(25);
    root.left.right.right = newNode(45);
    root.right.left = newNode(30);
    root.right.right = newNode(35);
    System.out.println(findDistance(root, 45));
}
}
// This code is contributed by Rajput-Ji

Python 3

# Python program to find distance of a given
# node from root.
from collections import deque
# A tree binary node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
# Function to find distance of a node from root
# root : root of the Tree
# key : data whose distance to be calculated
def findDistance(root: Node, key: int) -> int:
    # base case
    if root is None:
        return -1
    # If the key is present at root,
    # distance is zero
    if root.data == key:
        return 0
    # Iterating through tree using BFS
    q = deque()
    # pushing root to the queue
    q.append(root)
    # pushing marker to the queue
    q.append(None)
    # Variable to store count of level
    levelCount = 0
    while q:
        temp = q[0]
        q.popleft()
        # if node is marker, push marker to queue
        # else, push left and right (if exists)
        if temp is None and q:
            q.append(None)
            # Increment levelCount, while moving
            # to new level
            levelCount += 1
        elif temp:
            # If node at current level is Key,
            # return levelCount
            if temp.data == key:
                return levelCount
            if temp.left:
                q.append(temp.left)
            if temp.right:
                q.append(temp.right)
    # If key is not found
    return -1
# Driver Code
if __name__ == "__main__":
    root = Node(5)
    root.left = Node(10)
    root.right = Node(15)
    root.left.left = Node(20)
    root.left.right = Node(25)
    root.left.right.right = Node(45)
    root.right.left = Node(30)
    root.right.right = Node(35)
    print(findDistance(root, 45))
# This code is contributed by
# sanjeev2552

C

// C# program to find distance of a given
// node from root.
using System;
using System.Collections.Generic;
class GFG
{
// A Binary Tree Node
class Node
{
    public int data;
    public Node left, right;
};
// A utility function to create a new Binary
// Tree Node
static Node newNode(int item)
{
    Node temp = new Node();
    temp.data = item;
    temp.left = temp.right = null;
    return temp;
}
/* Function to find distance of a node from root
* root : root of the Tree
* key : data whose distance to be calculated*/
static int findDistance(Node root, int key)
{
    // base case
    if (root == null)
    {
        return -1;
    }
    // If the key is present at root,
    // distance is zero
    if (root.data == key)
        return 0;
    // Iterating through tree using BFS
    Queue q = new Queue();
    // adding root to the queue
    q.Enqueue(root);
    // adding marker to the queue
    q.Enqueue(null);
    // Variable to store count of level
    int levelCount = 0;
    while (q.Count!=0)
    {
        Node temp = q.Peek();
        q.Dequeue();
        // if node is marker, push marker to queue
        // else, push left and right (if exists)
        if (temp == null && q.Count!=0)
        {
            q.Enqueue(null);
            // Increment levelCount, while moving
            // to new level
            levelCount++;
        }
        else if (temp != null)
        {
            // If node at current level is Key,
            // return levelCount
            if (temp.data == key)
                return levelCount;
            if (temp.left != null)
                q.Enqueue(temp.left);
            if (temp.right != null)
                q.Enqueue(temp.right);
        }
    }
    // If key is not found
    return -1;
}
// Driver Code
public static void Main(String[] args)
{
    Node root = newNode(5);
    root.left = newNode(10);
    root.right = newNode(15);
    root.left.left = newNode(20);
    root.left.right = newNode(25);
    root.left.right.right = newNode(45);
    root.right.left = newNode(30);
    root.right.right = newNode(35);
    Console.WriteLine(findDistance(root, 45));
}
}
// This code is contributed by Princi Singh

java 描述语言


Output: 

3

推荐阅读
  • 实用正则表达式有哪些
    小编给大家分享一下实用正则表达式有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下 ... [详细]
  • 深入解析Java枚举及其高级特性
    本文详细介绍了Java枚举的概念、语法、使用规则和应用场景,并探讨了其在实际编程中的高级应用。所有相关内容已收录于GitHub仓库[JavaLearningmanual](https://github.com/Ziphtracks/JavaLearningmanual),欢迎Star并持续关注。 ... [详细]
  • 在高并发需求的C++项目中,我们最初选择了JsonCpp进行JSON解析和序列化。然而,在处理大数据量时,JsonCpp频繁抛出异常,尤其是在多线程环境下问题更为突出。通过分析发现,旧版本的JsonCpp存在多线程安全性和性能瓶颈。经过评估,我们最终选择了RapidJSON作为替代方案,并实现了显著的性能提升。 ... [详细]
  • 本题探讨了在一个有向图中,如何根据特定规则将城市划分为若干个区域,使得每个区域内的城市之间能够相互到达,并且划分的区域数量最少。题目提供了时间限制和内存限制,要求在给定的城市和道路信息下,计算出最少需要划分的区域数量。 ... [详细]
  • JavaScript 基础语法指南
    本文详细介绍了 JavaScript 的基础语法,包括变量、数据类型、运算符、语句和函数等内容,旨在为初学者提供全面的入门指导。 ... [详细]
  • 2018-2019学年第六周《Java数据结构与算法》学习总结
    本文总结了2018-2019学年第六周在《Java数据结构与算法》课程中的学习内容,重点介绍了非线性数据结构——树的相关知识及其应用。 ... [详细]
  • PHP 实现多级树形结构:构建无限层级分类系统
    在众多管理系统中,如菜单、分类和部门等模块,通常需要处理层级结构。为了高效管理和展示这些层级数据,本文将介绍如何使用 PHP 实现多级树形结构,并提供代码示例以帮助开发者轻松实现无限分级。 ... [详细]
  • 采用IKE方式建立IPsec安全隧道
    一、【组网和实验环境】按如上的接口ip先作配置,再作ipsec的相关配置,配置文本见文章最后本文实验采用的交换机是H3C模拟器,下载地址如 ... [详细]
  • 目录一、salt-job管理#job存放数据目录#缓存时间设置#Others二、returns模块配置job数据入库#配置returns返回值信息#mysql安全设置#创建模块相关 ... [详细]
  • Coursera ML 机器学习
    2019独角兽企业重金招聘Python工程师标准线性回归算法计算过程CostFunction梯度下降算法多变量回归![选择特征](https:static.oschina.n ... [详细]
  • 全面解析运维监控:白盒与黑盒监控及四大黄金指标
    本文深入探讨了白盒和黑盒监控的概念,以及它们在系统监控中的应用。通过详细分析基础监控和业务监控的不同采集方法,结合四个黄金指标的解读,帮助读者更好地理解和实施有效的监控策略。 ... [详细]
  • 本文详细介绍了 org.apache.commons.io.IOCase 类中的 checkCompareTo() 方法,通过多个代码示例展示其在不同场景下的使用方法。 ... [详细]
  • 使用lambda表达式排序Collections.sort(temp,(Stringa,Stringb)-{returnb.compareTo(a);});Collections ... [详细]
  • 利用决策树预测NBA比赛胜负的Python数据挖掘实践
    本文通过使用2013-14赛季NBA赛程与结果数据集以及2013年NBA排名数据,结合《Python数据挖掘入门与实践》一书中的方法,展示如何应用决策树算法进行比赛胜负预测。我们将详细讲解数据预处理、特征工程及模型评估等关键步骤。 ... [详细]
  • Nginx 反向代理与负载均衡实验
    本实验旨在通过配置 Nginx 实现反向代理和负载均衡,确保从北京本地代理服务器访问上海的 Web 服务器时,能够依次显示红、黄、绿三种颜色页面以验证负载均衡效果。 ... [详细]
author-avatar
daoyuanzhi
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有