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

检查二叉树中子和属性的迭代方法

检查二叉树中子和属性的迭代方法原文:https://www.

检查二叉树中子和属性的迭代方法

原文:https://www . geesforgeks . org/迭代方法检查孩子-二进制树中的属性总和/

给定一个二叉树,编写一个函数,如果树满足以下属性,则返回 true:
对于每个节点,数据值必须等于左右子节点中数据值的总和。对于空子代,将数据值视为 0。
例:

Input :
10
/ \
8 2
/ \ \
3 5 2
Output : Yes
Input :
5
/ \
-2 7
/ \ \
1 6 7
Output : No

我们已经讨论了递归方法。在这篇文章中,讨论了一种迭代方法。
方法:想法是用一个队列对二叉树进行级别顺序遍历,同时检查每个节点:


  1. 如果当前节点有两个子节点,并且当前节点等于其左右子节点之和。

  2. 如果当前节点刚刚离开子节点,并且当前节点等于它的左子节点。

  3. 如果当前节点正好有一个右子节点,并且当前节点等于它的右子节点。

以下是上述方法的实现:

C++

// C++ program to check children sum property
#include
using namespace std;
// A binary tree node
struct Node {
    int data;
    Node *left, *right;
};
// Utility function to allocate memory for a new node
Node* newNode(int data)
{
    Node* node = new (Node);
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
// Function to check if the tree holds
// children sum property
bool CheckChildrenSum(Node* root)
{
    queue q;
    // Push the root node
    q.push(root);
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        // If the current node has both left and right children
        if (temp->left && temp->right) {
            // If the current node is not equal to
            // the sum of its left and right children
            // return false
            if (temp->data != temp->left->data + temp->right->data)
                return false;
            q.push(temp->left);
            q.push(temp->right);
        }
        // If the current node has right child
        else if (!temp->left && temp->right) {
            // If the current node is not equal to
            // its right child return false
            if (temp->data != temp->right->data)
                return false;
            q.push(temp->right);
        }
        // If the current node has left child
        else if (!temp->right && temp->left) {
            // If the current node is not equal to
            // its left child return false
            if (temp->data != temp->left->data)
                return false;
            q.push(temp->left);
        }
    }
    // If the given tree has children
    // sum property return true
    return true;
}
// Driver code
int main()
{
    Node* root = newNode(10);
    root->left = newNode(8);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(5);
    root->right->right = newNode(2);
    if (CheckChildrenSum(root))
        printf("Yes");
    else
        printf("No");
    return 0;
}

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

// Java program to check children sum property
import java.util.*;
class GFG
{
// A binary tree node
static class Node
{
    int data;
    Node left, right;
}
// Utility function to allocate memory for a new node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
// Function to check if the tree holds
// children sum property
static boolean CheckChildrenSum(Node root)
{
    Queue q = new LinkedList();
    // add the root node
    q.add(root);
    while (q.size() > 0)
    {
        Node temp = q.peek();
        q.remove();
        // If the current node has both left and right children
        if (temp.left != null && temp.right != null)
        {
            // If the current node is not equal to
            // the sum of its left and right children
            // return false
            if (temp.data != temp.left.data + temp.right.data)
                return false;
            q.add(temp.left);
            q.add(temp.right);
        }
        // If the current node has right child
        else if (temp.left == null && temp.right != null)
        {
            // If the current node is not equal to
            // its right child return false
            if (temp.data != temp.right.data)
                return false;
            q.add(temp.right);
        }
        // If the current node has left child
        else if (temp.right == null && temp.left != null)
        {
            // If the current node is not equal to
            // its left child return false
            if (temp.data != temp.left.data)
                return false;
            q.add(temp.left);
        }
    }
    // If the given tree has children
    // sum property return true
    return true;
}
// Driver code
public static void main(String args[])
{
    Node root = newNode(10);
    root.left = newNode(8);
    root.right = newNode(2);
    root.left.left = newNode(3);
    root.left.right = newNode(5);
    root.right.right = newNode(2);
    if (CheckChildrenSum(root))
        System.out.printf("Yes");
    else
        System.out.printf("No");
}
}
// This code is contributed by Arnab Kundu

Python 3

# Python3 program to check
# children sum property
# A binary tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
# Function to check if the tree holds
# children sum property
def CheckChildrenSum(root):
    q = []
    # Push the root node
    q.append(root)
    while len(q) != 0:
        temp = q.pop()
        # If the current node has both
        # left and right children
        if temp.left and temp.right:
            # If the current node is not equal
            # to the sum of its left and right
            # children, return false
            if (temp.data != temp.left.data +
                             temp.right.data):
                return False
            q.append(temp.left)
            q.append(temp.right)
        # If the current node has right child
        elif not temp.left and temp.right:
            # If the current node is not equal
            # to its right child return false
            if temp.data != temp.right.data:
                return False
            q.append(temp.right)
        # If the current node has left child
        elif not temp.right and temp.left:
            # If the current node is not equal
            # to its left child return false
            if temp.data != temp.left.data:
                return False
            q.append(temp.left)
    # If the given tree has children
    # sum property return true
    return True
# Driver code
if __name__ == "__main__":
    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)
    root.left.left = Node(3)
    root.left.right = Node(5)
    root.right.right = Node(2)
    if CheckChildrenSum(root):
        print("Yes")
    else:
        print("No")
# This code is contributed
# by Rituraj Jain

C

// C# program to check children sum property
using System;
using System.Collections.Generic;
class GFG
{
// A binary tree node
public class Node
{
    public int data;
    public Node left, right;
}
// Utility function to allocate
// memory for a new node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
// Function to check if the tree holds
// children sum property
static Boolean CheckChildrenSum(Node root)
{
    Queue q = new Queue();
    // add the root node
    q.Enqueue(root);
    while (q.Count > 0)
    {
        Node temp = q.Peek();
        q.Dequeue();
        // If the current node has both
        // left and right children
        if (temp.left != null &&
            temp.right != null)
        {
            // If the current node is not equal to
            // the sum of its left and right children
            // return false
            if (temp.data != temp.left.data +
                             temp.right.data)
                return false;
            q.Enqueue(temp.left);
            q.Enqueue(temp.right);
        }
        // If the current node has right child
        else if (temp.left == null &&
                 temp.right != null)
        {
            // If the current node is not equal to
            // its right child return false
            if (temp.data != temp.right.data)
                return false;
            q.Enqueue(temp.right);
        }
        // If the current node has left child
        else if (temp.right == null &&
                 temp.left != null)
        {
            // If the current node is not equal to
            // its left child return false
            if (temp.data != temp.left.data)
                return false;
            q.Enqueue(temp.left);
        }
    }
    // If the given tree has children
    // sum property return true
    return true;
}
// Driver code
public static void Main(String []args)
{
    Node root = newNode(10);
    root.left = newNode(8);
    root.right = newNode(2);
    root.left.left = newNode(3);
    root.left.right = newNode(5);
    root.right.right = newNode(2);
    if (CheckChildrenSum(root))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
// This code is contributed by Rajput-Ji

java 描述语言


Output: 

Yes

时间复杂度 : O(N),其中 N 为二叉树中的节点总数。
辅助空间: O(N)


推荐阅读
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 本文讨论了一个数列求和问题,该数列按照一定规律生成。通过观察数列的规律,我们可以得出求解该问题的算法。具体算法为计算前n项i*f[i]的和,其中f[i]表示数列中有i个数字。根据参考的思路,我们可以将算法的时间复杂度控制在O(n),即计算到5e5即可满足1e9的要求。 ... [详细]
  • 使用nodejs爬取b站番剧数据,计算最佳追番推荐
    本文介绍了如何使用nodejs爬取b站番剧数据,并通过计算得出最佳追番推荐。通过调用相关接口获取番剧数据和评分数据,以及使用相应的算法进行计算。该方法可以帮助用户找到适合自己的番剧进行观看。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • 本文介绍了C++中省略号类型和参数个数不确定函数参数的使用方法,并提供了一个范例。通过宏定义的方式,可以方便地处理不定参数的情况。文章中给出了具体的代码实现,并对代码进行了解释和说明。这对于需要处理不定参数的情况的程序员来说,是一个很有用的参考资料。 ... [详细]
  • javascript  – 概述在Firefox上无法正常工作
    我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • C++字符字符串处理及字符集编码方案
    本文介绍了C++中字符字符串处理的问题,并详细解释了字符集编码方案,包括UNICODE、Windows apps采用的UTF-16编码、ASCII、SBCS和DBCS编码方案。同时说明了ANSI C标准和Windows中的字符/字符串数据类型实现。文章还提到了在编译时需要定义UNICODE宏以支持unicode编码,否则将使用windows code page编译。最后,给出了相关的头文件和数据类型定义。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • 第四章高阶函数(参数传递、高阶函数、lambda表达式)(python进阶)的讲解和应用
    本文主要讲解了第四章高阶函数(参数传递、高阶函数、lambda表达式)的相关知识,包括函数参数传递机制和赋值机制、引用传递的概念和应用、默认参数的定义和使用等内容。同时介绍了高阶函数和lambda表达式的概念,并给出了一些实例代码进行演示。对于想要进一步提升python编程能力的读者来说,本文将是一个不错的学习资料。 ... [详细]
  • 热血合击脚本辅助工具及随机数生成器源码分享
    本文分享了一个热血合击脚本辅助工具及随机数生成器源码。游戏脚本能够实现类似真实玩家的操作,但信息量有限且操作不可控。热血合击脚本辅助工具可以帮助玩家自动刷图、换图拉怪等操作,并提供了雷电云手机的扩展服务。此外,还介绍了使用mt_rand函数作为随机数生成器的代码示例。 ... [详细]
  • 本文详细介绍了如何使用MySQL来显示SQL语句的执行时间,并通过MySQL Query Profiler获取CPU和内存使用量以及系统锁和表锁的时间。同时介绍了效能分析的三种方法:瓶颈分析、工作负载分析和基于比率的分析。 ... [详细]
author-avatar
岁月无言0106
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有