在给定总和K的二叉树中找到级别

Description:

描述:

The article describes how to find the level in a binary tree with given sum K? This is an interview coding problem came in Samsung, Microsoft.

本文介绍了如何在给定总和K下在二叉树中找到级别 ? 这是一个面试编码问题,来自三星,微软。

Problem statement:

问题陈述:

Given a binary tree and an integer K, output the level no of the tree which sums to K. Assume root level is level 0.

给定一棵二叉树和一个整数K ,输出该树的级数之和为K。 假设根级别为0

Solution

Algorithm:

算法:

One of the popular traversal techniques to solve this kind of problems is level order tree traversal (Read more: Level Order Traversal on a Binary Tree) where we use the concept of BFS with some modifications.

解决此类问题的一种流行的遍历技术是级别顺序树遍历(更多内容: 二叉树上的级别顺序遍历 ),其中我们使用了经过修改的BFS概念。

1. Set a variable level=0 & declare a variable of type tree* named temp. level is a flag for the current level & temp stores tree node to be processed.

1.设置变量level = 0并声明一个名为temp的 tree *类型的变量。 级别是当前级别和临时存储要处理的树节点的标志。

2. Set cur_sum=0

2.设置cur_sum = 0

3. if(!root) // root is NULL
return -1; //no such level exists

3. if(!root) //根为NULL
返回-1; //不存在这样的级别

4. q=createQueue() //to store pointers to tree node

4. q = createQueue() //存储指向树节点的指针

5. EnQueue(q,root);

5. EnQueue(q,root);

6. EnQueue(q,NULL);

6. EnQueue(q,NULL);

Every time, we EnQueue a NULL to reflect the end of current level. Same way while processing when NULL is found, it reveals that end of current level.

每次,我们将NULL排队以反映当前级别的结束。 发现NULL时进行处理的方式相同,它显示当前级别的末尾。

7. while( q is not empty)
temp=DeQueue(q);
if(temp==NULL){ //end of current level
if (cur_sum==K) // current level sum is equal to K
Return level; //return level no (root is at 0 level)
else {
Set cur_sum =0; // for next level
If(q is not empty)
// to reflect end of next level which 
// will be processed in next iteration
EnQueue(q,NULL)
Increase level //increase level count
}
}
Else{
cur_sum+=temp->data; //sum the level
//do level order traversal
If(temp->left)
EnQueue(temp->left);
If(temp->right)
EnQueue (temp->right);
}
End while loop

8. If program control comes out of while loop then surely no level has a sum K. Thus print no level has sum K

8.如果程序控制从while循环中出来,那么肯定没有水平的总和为K。 因此打印无级别的总和为K

tree image 1

Example:

例:

Here the level sums are:
For level 0: 2
For level 1: 12
For level 2: 17
For level 3: 20
Thus if K is 12 our program will print level 1

C ++代码在给定总和为K的二叉树中找到级别 (C++ code to find the level in a binary tree with given sum K)

#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class tree{
public:
int data;
tree *left;
tree *right;
};
int findLevel( tree *root,int K){
queue<tree*> q;  // using stl
tree* temp;
//counting level no & initializing cur_sum
int level=0,cur_sum=0; 
//EnQueue root
q.push(root); 
//EnQueue NULL to inticate end of 0 level
q.push(NULL);
while(!q.empty()){
//DeQueueing using STL
temp=q.front(); 
q.pop();
if(temp==NULL){
//if current level sum equals to K
if(cur_sum==K) 
return level;//return level no
//ifn't then set cur_sum to 0 for further levels
cur_sum=0; 
if(!q.empty())
q.push(NULL);
level++;
}
else{
//level order traversal
cur_sum+=temp->data; //sum thd level
if(temp->left)
q.push(temp->left); //EnQueue
if(temp->right)
q.push(temp->right); //EnQueue
}
}
return -1;
}
// creating new node
tree* newnode(int data)  
{ 
tree* node = (tree*)malloc(sizeof(tree)); 
node->data = data; 
node->left = NULL; 
node->right = NULL; 
return(node); 
} 
int main() 
{ 
//**same tree is builted as shown in example**
int c,K;
cout<<"Tree is built like the example aforesaid"<<endl;
cout<<"input K....."<<endl;
cin>>K;
tree *root=newnode(2); 
root->left= newnode(7); 
root->right= newnode(5); 
root->right->right=newnode(9);
root->right->right->left=newnode(4);
root->left->left=newnode(2); 
root->left->right=newnode(6);
root->left->right->left=newnode(5);
root->left->right->right=newnode(11);
cout<<"finding if any level exists......"<<endl; 
c=findLevel(root,K);
if(c>=0)
cout<<"level is found and it is level "<<c<<endl;
else
cout<<"level not found, no such tree level exists";
return 0; 
} 

Output

输出量

First run:
Tree is built like the example aforesaid 
input K..... 
20 
finding if any level exists......
level is found and it is level 3 
Second run:
Tree is built like the example aforesaid 
input K..... 
25 
finding if any level exists......
level not found, no such tree level exists

翻译自: https://www.includehelp.com/icp/find-the-level-in-a-binary-tree-with-given-sum-k.aspx

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/news/379690.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PostgreSQL学习手册(数据库维护) 转

原文&#xff1a; PostgreSQL学习手册(数据库维护)一、恢复磁盘空间&#xff1a;在PostgreSQL中&#xff0c;使用delete和update语句删除或更新的数据行并没有被实际删除&#xff0c;而只是在旧版本数据行的物理地址上将该行的状态置为已删除或已过期。因此当数据表中的数据变化…

++i与i++的根本性区别(两个代码对比搞定)

首先来看i 代码如下&#xff1a; #include <stdio.h> #include <stdlib.h> int main() {int i0;int ai;printf("%d\n",a);printf("%d\n\n\n",i);return 0; }输出结果如下&#xff1a; 解释&#xff1a;i其实是两行代码的简写形式&#xff0c…

国企和外企的比较

由于本人在外企&#xff0c;而很多朋友在国企&#xff0c;因此我个人的说法应该还是有一定的权威性。 首先&#xff0c;国企和外企不能一概而论。正如任何事物都有三六九等&#xff0c;这个&#xff0c;只能在同等级别上进行比较。 国企分类&#xff1a; 一等国企&#xff1…

Python | 使用matplotlib.pyplot创建线图

Problem statement: Write a program in python (using matplotlib.pyplot) to create a line plot. 问题陈述&#xff1a;用python编写程序(使用matplotlib.pyplot)以创建线图。 Program: 程序&#xff1a; import matplotlib.pyplot as pltx [1,2,3,4,5,6,7,8,9,10]y [3,…

QI(接口查询)

接触AE一段时间了&#xff0c;总的来说收获不少&#xff0c;今天仔细分析了一下AE开发中经常会用到的QI即接口查询&#xff0c;有了自己的一些理解。 COM类至少有一个接口。事实上一般它们有好几个接口。即一个类经常会实现多个接口&#xff08;一个类无法继承多个类&#xff0…

linux内核设计与实现---从内核出发

获取、编译、安装内核1 获取内核源码安装内核源代码何处安装源码使用补丁2 内核源码树3 编译内核减少编译的垃圾信息衍生多个编译作业安装内核启用指定内核作为引导4 内核开发的特点没有libc库头文件没有内存保护机制容积小而固定的栈1 获取内核源码 在linux内核官方网站http:…

MySQL在DOS下的基本命令操作

启动net start mysql 重置root密码 方法一:在my.ini的[mysqld]字段加入&#xff1a; skip-grant-tables 重启mysql服务&#xff0c;这时的mysql不需要密码即可登录数据库然后进入mysql mysql>use mysql;mysql>更新 user set passwordpassword(新密码) WHERE Userroot; …

strlen的神奇实现

https://blog.delphij.net/2012/04/freebsd-strlen3.html 与 Pascal 等语言不同&#xff0c;C 的字符串并不保存串的长度&#xff0c;而是在字符串末尾以 nul 字符&#xff08;\0&#xff09;来表示字符串结束。这个设计决策是上世纪 60 年代作出的&#xff0c;有都市传说是为了…

python求和_Python程序查找特殊求和系列的解决方案

python求和We are going to design a special sum series function which has following characteristics: 我们将设计一个特殊的求和系列函数&#xff0c;该函数具有以下特征&#xff1a; f(0) 0f(1) 1f(2) 1f(3) 0f(x) f(x-1) f(x-3)Python solution of the above sum…

linux内核设计与实现---进程管理

进程管理1 进程描述符及任务结构分配进程描述符进程描述符的存放进程状态设置当前进程状态进程上下文进程家族树2 进程创建写时拷贝fork()vfork()3 线程在Linux中的实现内核线程4 进程终结删除进程描述符孤儿进程造成的进退微谷5 小结进程的另一个名字叫做任务&#xff08;task…

JS错误代码解释大全+VBS错误代码解释大全

JScript 运行时错误 JScript 运行时错误是指当 JScript 脚本试图执行一个系统不能运行的动作时导致的错误。当正在运行脚本、计算变量表达式、或者正在动态分配内存时出现 JScript 运行时错误时。 错误号 描述 5029 数组长度必须为一有限正整数 5030 必须赋给数组长度一个有…

生日蜡烛(蓝桥杯)

某君从某年开始每年都举办一次生日party&#xff0c;并且每次都要吹熄与年龄相同根数的蜡烛。 现在算起来&#xff0c;他一共吹熄了236根蜡烛。 请问&#xff0c;他从多少岁开始过生日party的&#xff1f; 请填写他开始过生日party的年龄数。 注意&#xff1a;你提交的应该是…

python日历模块_Python日历模块| firstweekday()方法与示例

python日历模块Python calendar.firstweekday()方法 (Python calendar.firstweekday() Method) firstweekday() method is an inbuilt method of the calendar module in Python. It works on simple text calendars and returns the current setting for the weekday to start…

php 处理 mysql to json, 前台js处理

public function GetJson(){$query"select * from table";$result mysql_query($query);$rows array();while($row mysql_fetch_array($result)){$rows [] $row;}echo json_encode($rows); } js处理 $.get( "./bll.php", option,function(data ) {var j…

Linux内核设计与实现---进程调度

进程调度1 策略I/O消耗型和处理器消耗型的进程进程优先级时间片进程抢占2 Linux调度算法可执行队列优先级数组重新计算时间片schedule()计算优先级和时间片睡眠和唤醒负载平衡程序3 抢占和上下文切换用户抢占内核抢占4 实时5 与调度相关的系统调用与调度策略和优先级相关的系统…

ServletContext(核心内容)

什么是ServletContext对象 ServletContext代表是一个web应用的环境&#xff08;上下文&#xff09;对象&#xff0c;ServletContext对象 内部封装是该web应用的信息&#xff0c;ServletContext对象一个web应用只有一个 一个web应用有多个servlet对象 ServletContext对象的生…

【转载】[TC]飞船动画例子--《C高级实用程序设计》

【声明和备注】本例子属于转载来源于《C高级实用程序设计》&#xff08;王士元&#xff0c;清华大学出版社&#xff09;第11章&#xff0c;菜单设计与动画技术&#xff0c;第11.5节&#xff0c;一个动画例子。 本例讲解的是在一个繁星背景下&#xff0c;一个由经纬线组成的蓝色…

math.sqrt 有问题_JavaScript中带有示例的Math.SQRT2属性

math.sqrt 有问题JavaScript | Math.SQRT2属性 (JavaScript | Math.SQRT2 Property) Math.SQRT2 is a property in math library of JavaScript that is used to find the value of square root of 2. It is generally used to solve problems related to circular figures. Ma…

Linux内核设计与实现---系统调用

系统调用1 API、POSIX和C库2 系统调用系统调用号3 系统调用处理程序指定恰当的系统调用参数传递4 系统调用的实现参数验证5 系统调用上下文绑定一个系统调用的最后步骤从用户空间访问系统调用为什么不通过系统调用的方式实现1 API、POSIX和C库 API&#xff1a;应用编程接口。一…

内核编译配置选项含义

Linux 2.6.19.x 内核编译配置选项简介 作者&#xff1a;金步国 版权声明 本文作者是一位自由软件爱好者&#xff0c;所以本文虽然不是软件&#xff0c;但是本着 GPL 的精神发布。任何人都可以自由使用、转载、复制和再分发&#xff0c;但必须保留作者署名&#xff0c;亦不得对声…