在每次迭代中打印并删除给定二叉树的叶节点
给定一棵二叉树,任务是:
- 打印所有叶节点,然后将它们全部删除。
- 重复这个过程,直到树变空。
例子:
Input:
1
/. \
2 3
/ \
4 5
Output:
Iteration 1: 4 5 3
Iteration 2: 2
Iteration 3: 1
Explanation: The leaf nodes initially were 4, 5 and 3.
When those were deleted only node with no child is 2.
So the leaf node is 2. After 2 is deleted 1 is the only node of the tree.
So 1 is deleted in the 3rd and last iteration.
Input:
1
/
2
/
3
Output:
Iteration 1: 3
Iteration 2: 2
Iteration 3: 1
朴素方法:这个问题可以通过多次使用任何遍历算法来解决,并且在每次迭代中简单地打印并删除所有叶节点。可以在此处找到此方法的参考。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效方法:高效解决问题的思路如下:
Instead of doing the traversal multiple time simply traverse only once and at the same time calculate the depth of each node.
Then sort the nodes as per depth and will get first leaf nodes at depth 0, second iteration leaf nodes at depth 1 and so on.
请按照以下步骤解决问题:
- 使用 DFS 递归遍历树。
- 对于任何节点:
- 找到左子树深度。
- 找到正确的子树深度。
- 节点深度 = max(leftSubtreeDepth, rightSubtreeDepth) +1
- 根据深度将节点值存储在地图中(深度是键,节点的值作为向量中的元素)
下面是上述方法的实现。
C++
// C++ program to print and
// remove leaf nodes
#include
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
map > resultMap;
// Function to store depth of each nodes
int fillMap(Node* root)
{
if (root == nullptr)
return 0;
int LsubTreeDepth = fillMap(root->left);
int RsubTreeDepth = fillMap(root->right);
int depth = max(LsubTreeDepth,
RsubTreeDepth)
+ 1;
resultMap[depth].push_back(root->data);
return depth;
}
// Print and remove leaf nodes
void printLeafNodes(Node* root)
{
// If node is null, return
if (!root)
return;
// maxDepth from tree
int maxDepth = fillMap(root);
for (int i = 1; i <= maxDepth; i++) {
vector tempVector
= resultMap[i];
int vSize = tempVector.size();
// Print leaf nodes
// from each iteration
cout << "Iteration " << i << " : ";
for (int j = 0; j < vSize; j++)
cout << tempVector[j] << " ";
cout << "\n";
}
}
// Utility function to
// create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver Code
int main()
{
// Create binary tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Print leaf nodes of the given tree
printLeafNodes(root);
return 0;
}
Iteration 1 : 4 5 3
Iteration 2 : 2
Iteration 3 : 1
时间复杂度: O(N)
辅助空间: O(N)