二叉树。我有代码,需要一些帮助 [英] Binary tree. I have code, need little help

查看:99
本文介绍了二叉树。我有代码,需要一些帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个程序在二叉树中搜索,只有一个孩子的结。我的问题是,如何修复它以便它可以搜索有两个孩子的结?



Hi, this program searches in binary tree, knots with only one child. My question is, how to fix it so it can searches for knots with two children?

#include <iostream>
using namespace std;

struct elem {
	int key;
	elem *left;
	elem *right;
} *root = NULL;

void preorder(elem *t) 
{
	if (t)

	{
		cout << t->key << "\t";
		preorder(t->left);
		preorder(t->right);
	}

}

void inorder(elem *t) 
{
	if (t)
	{
		inorder(t->left);
		cout << t->key << "\t";
		inorder(t->right);
	}
}

void add(int n, elem *&t)
{
	if (t == NULL)
	{
		t = new elem; t->key = n;
		t->left = NULL; t->right = NULL;
	}
	else
	{
		if (t->key>n)
			add(n, t->left);
		else if (t->key<n)
			add(n, t->right);
	}
}

void postorder(elem *t) 
{
	if (t)
	{
		postorder(t->left);
		postorder(t->right);
		cout << t->key << "\t";
	}
}


int height(elem * t)
{
	if (t == NULL)
		return -1;
	int u = height(t->left);
	int v = height(t->right);
	if (u > v)
		return u + 1;
	return v + 1;
}


void printnode(int n, int h)
{
	for (int i = 0; i<h; i++)
		cout << "\t";
	cout << n << endl;
}


void show(elem *t, int h)
{
	if (t == NULL)
		return;
	show(t->right, h + 1);
	printnode(t->key, h);
	show(t->left, h + 1);
}


int count(elem *t)
{
	if (t == NULL) return 0;  return count(t->left) + count(t->right) + 1;
}

 
int count1(elem *t)
{
	if (t == NULL) return 0;
	return count1(t->left) + count1(t->right) + (t->left == NULL) ^ (t->right == NULL);
}

void main()
{
	int a;
	cout << "\n Add elements" << endl;

	do
	{
		cin >> a;
		if (a>0)
			add(a, root);
	} while (a>0);

	int r = count(root);
	cout << "Number of knots " << r << endl;
	int r1 = count1(root);
	cout << "Number of knots with one child" << r1;
	cout << endl;
	cout << endl;
	show(root, 0);
	system("pause");
}





我的尝试:



我试图改变一些东西,但它们都没有像我想的那样工作。



What I have tried:

I have tried to change some things, but none of them worked like i want.

推荐答案

你的问题是运算符优先:+运算符有一个优先于^运算符,以便将表达式计算为



Your problem is operator precedence: + operator have a priority over ^ operator so that your expression is evaluated as

return (count1(t->left) + count1(t->right) + (t->left == NULL)) ^ (t->right == NULL);





要纠正此问题,您需要使用括号来更改评估顺序:





To correct this, you need to use brackets to change the evaluation order:

return count1(t->left) + count1(t->right) + ((t->left == NULL) ^ (t->right == NULL));


抱歉,该修复程序适用于您的初始程序(搜索具有唯一子节点的节点)。它包含运算符优先级错误。

如果要搜索包含两个子节点的节点,请改用此行:

Sorry, that fix was for your initial program (searching for nodes with the only child). It contained an operator precedence error.
If you want to search for nodes with two children, use this line instead:
return count1(t->left) + count1(t->right) + (t->left != NULL && t->right != NULL ? 1 : 0);


这篇关于二叉树。我有代码,需要一些帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆