使用 C++ 中的迭代法,从左到右打印二叉树中所有叶节点
在此示例中,我们得到了一个二叉树,我们需要使用迭代法从左到右打印二叉树的所有叶节点。
我们来举个例子来理解这个问题
输入 -

输出 - 1 4 7
为了使用迭代法解决这个问题,我们将使用深度优先搜索 (DFS)。为了遍历树,我们将从根节点开始,然后检查它是否为叶节点,如果是,则打印该节点,否则找到它的子树,并遍历子子树以查找所有叶节点。
示例
以下代码将实现我们的解决方案 -
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
Node* insertNode(int data) {
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
void printLTRLeafNodes(Node *root){
if (!root)
return;
if (!root->left && !root->right) {
cout<<root->data<<"\t";
return;
}
if (root->left)
printLTRLeafNodes(root->left);
if (root->right)
printLTRLeafNodes(root->right);
}
int main(){
Node *root = insertNode(21);
root->left = insertNode(5);
root->right = insertNode(36);
root->left->left = insertNode(2);
root->right->left = insertNode(13);
root->right->right = insertNode(4);
root->right->left->left = insertNode(76);
root->right->left->right = insertNode(9);
root->right->right->left = insertNode(17);
root->right->right->right = insertNode(2);
cout<<"Leaf Nodes of the tree from left to rigth are :\n";
printLTRLeafNodes(root);
return 0;
}输出
Leaf Nodes of the tree from left to right are − 2 76 9 17 2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP