Diagonal Traversal of Binary Tree
Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line. If the diagonal element are present in two different subtress then left subtree diagonal element should be taken first and then right subtree.?
Approach :
vector<int> diagonal(Node *root)
{
vector<int>ans;
if(root == NULL){
return ans ;
}
queue<Node*>q;
q.push(root);
while(!q.empty()){
Node* frontNode = q.front();
q.pop();
while(frontNode != NULL){
ans.push_back(frontNode->data);
if(frontNode->left){
q.push(frontNode->left);
}
frontNode = frontNode->right;
}
}
return ans;
}
领英推荐
The result is stored in the vector ans, which contains the diagonal elements in the desired order.
Time Complexity: O(N)
Space Complexity: O(N)
Student || 3??Codechef (Max rating -1629) || 5?? C++/Problem Solving Hackerrank ||Codeforces Max Rating -1166|| CP Enthusiast || Problem Solver & Daily Streak Gold??Codechef || 300+Codechef || 200+ Codeforces
1 个月Very informative??