?? Bottom View of Binary Tree
The task is to print the bottom view of binary tree. Bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom.
Approach:
To solve the problem, we use a level order traversal (breadth-first search) combined with tracking the horizontal distance for each node. The key steps are:
Steps:
领英推荐
vector <int> bottomView(Node *root) {
vector<int>ans;
if(root == NULL){
return ans;
}
map<int,int>topNode;
queue<pair<Node*, int>>q;
q.push(make_pair(root, 0));
while(!q.empty()){
pair<Node*, int>temp = q.front();
q.pop();
Node* frontNode = temp.first;
int hd = temp.second;
topNode[hd] = frontNode->data;
if(frontNode->left){
q.push(make_pair(frontNode->left, hd-1));
}
if(frontNode->right){
q.push(make_pair(frontNode->right, hd+1));
}
}
for(auto i:topNode){
ans.push_back(i.second);
}
return ans;
}
Time Complexity: O(N)
Space Complexity: O(N)