接受来自键盘的树节点以确定其高度

Accepting tree nodes from keyboard for determining it's height

本文关键字:高度 树节点 键盘      更新时间:2023-10-16

我有一个代码,可以通过硬编码来确定树的高度

我尝试使用类似容器的结构,但仍然没有成功,而不是发布我尝试过的接受输入的树节点,这实际上是混乱的,我决定发布带有硬编码树节点的代码,我需要的是程序接受来自键盘的树节点,并使用以下辅助程序描述进行输入

输入:

第一行是整数 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);
}