接受来自键盘的树节点以确定其高度
Accepting tree nodes from keyboard for determining it's height
我有一个代码,可以通过硬编码来确定树的高度
我尝试使用类似容器的结构,但仍然没有成功,而不是发布我尝试过的接受输入的树节点,这实际上是混乱的,我决定发布带有硬编码树节点的代码,我需要的是程序接受来自键盘的树节点,并使用以下辅助程序描述进行输入
输入:
第一行是整数 N,表示节点数。
对于接下来的几行中的每一行,有两个整数包括 a,b.b 是 a 的子项。
例:
5 // number of nodes
1 2
1 3
3 4
3 5
其中高度将为 3
// C++ program to find height of tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node
{
public:
int data;
node* left;
node* right;
};
/* Compute the "maxDepth" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth + 1);
else return(rDepth + 1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
// Driver code
int main()
{
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height of tree is " << maxDepth(root);
return 0;
}
由于输入通过其数据值标识父节点,因此我们需要一个辅助函数来查找它:
node *findNode(node *node, int data)
{
if (!node) return 0;
if (node->data == data) return node;
class node *found;
(found = findNode(node->left, data)) || (found = findNode(node->right, data));
return found;
}
然后我们可以对输入处理进行编码,例如:
node *node, *root = 0; // initially empty
int nn, a, b;
cin>>nn;
while (cin>>a>>b)
{
if (!root)
root = newNode(a),
node = root;
else
node = findNode(root, a);
if (!node->left) node->left = newNode(b);
else node->right = newNode(b);
}
相关文章:
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 没有从"树节点"到"树节点*"的可行转换
- 对树节点使用 CString 时出现内存泄漏
- 预分配的节点向量中的无锁树节点分配
- 接受来自键盘的树节点以确定其高度
- C++ Eclipse:二叉搜索树节点>数据=变量似乎不起作用
- C++错误(从不兼容的类型"void"分配给树节点*)
- UWP:在树节点中将文本设置为粗体
- 树节点之间的最大距离中的运行时错误
- 想要以最新的添加节点完整返回树节点的根
- 从GCC功能树节点中检索函数参数
- 如何映射数组元素以选择二进制树节点
- Boost::p tree - 访问列表中包含的属性树节点
- 二进制搜索树节点插入
- 根据其子节点的余额计算 AVL 树节点余额
- 检查树节点等于值
- 创建一个C++预排序迭代器,为循环提供树节点
- 递归后序遍历解除分配二叉树节点
- 创建模板树节点列表时出错
- 二叉搜索树节点的结构应该是什么