您好,欢迎访问一九零五行业门户网

迭代方法寻找二叉树的高度

二叉树是一种数据结构。二叉树的每个节点包含 0、1 或 2 个节点。因此,二叉树可以包含多个级别。
在这里,我们需要使用循环编写迭代代码来查找二叉树的高度。二叉树的总层数代表二叉树的高度。或者,我们可以说二叉树从根节点开始的最大深度就是二叉树的高度。
问题陈述 - 我们给出了一个二叉树。我们需要使用迭代的方法来求出给定二叉树的高度。
方法 1正如我们上面所说,二叉树的高度等于二叉树的总层数。我们将使用队列数据结构来遍历每一层的每个节点并找到树的最大深度。
算法第 1 步 - 定义“treenode”类,并添加“val”整型变量。另外,在类中定义“左”和“右”指针。
步骤 2- 定义 createnode() 函数来为树创建一个新节点。它创建一个新的treenode,用参数值初始化“val”,用空值初始化左指针和右指针。最后返回新创建的节点。
步骤 3 - findheight() 函数用于查找二叉树的高度。
第 4 步 - 定义“levelqueue”队列来存储当前级别的所有节点、“treeheight”、“n_cnt”变量和“temp”节点。
第 5 步− 如果头节点为 null,则返回 0。
第 6 步- 将头节点推送到“levelqueue”。
第 7 步- 使用“while”循环进行迭代,直到“levelqueue”变空。
第 8 步- 将“treeheight”增加 1,并用队列的大小初始化“n_cnt”,代表当前级别的总节点数。
第 9 步- 遍历队列的所有元素。
步骤 9.1 - 弹出队列的第一个元素。
步骤 9.2 − 如果当前节点存在左子节点,则将其插入队列。
步骤 9.3 − 如果当前节点存在右子节点,则将其插入队列。
步骤 9.4 - 从队列中删除第一个节点。
第 10 步- 返回“treeheight”变量的值。
示例#include <iostream>#include <queue>using namespace std;class treenode {public: int val; treenode *left; treenode *right;};treenode *createnode(int val) { //create a new node treenode *temp = new treenode(); temp->val = val; temp->left = null; temp->right = null; return temp;}int fidheight(treenode *head) { queue<treenode *> levelqueue; int treeheight = 0; // to store the tree height of the current binary tree int n_cnt = 0; // to store the total number of current level nodes. treenode *temp; // pointer to store the address of a node in the current level. // for empty binary tree if (head == null) { return 0; } // add root node to queue levelqueue.push(head); // traverse level of binary tree while (!levelqueue.empty()) { // for each level increment, the treeheight of the three treeheight++; n_cnt = levelqueue.size(); // add child nodes of all nodes at the current level while (n_cnt--) { temp = levelqueue.front(); // insert the left child node of the current node if (temp->left != null) { levelqueue.push(temp->left); } // insert the right child node of the current node if (temp->right != null) { levelqueue.push(temp->right); } // remove the current node levelqueue.pop(); } } return treeheight;}int main() { treenode *head = null; // adding nodes to binary tree. head = createnode(45); head->right = createnode(32); head->right->left = createnode(48); head->left = createnode(90); head->left->left = createnode(5); head->left->left->left = createnode(50); cout << the given binary tree's treeheight is << fidheight(head) << .; return 0;}
输出the given binary tree's treeheight is 4.
时间复杂度 - o(n) 遍历每个节点。
空间复杂度 - o(n) 在队列中存储节点。
解决任何问题时,迭代方法总是比递归方法更快。在这里,我们使用循环和队列来迭代地找到二叉树的最大深度或高度。然而,程序员可能会尝试编写递归方法的代码来查找二叉树的高度。
以上就是迭代方法寻找二叉树的高度的详细内容。
其它类似信息

推荐信息