Light is falling on a tree from left side you have to find all the nodes on which this light will fa

来源:互联网 发布:大连民族学院网络 编辑:程序博客网 时间:2024/05/16 02:13

思路:所求节点就是层序遍历中,每一层的第一个节点。

#include <vector>#include <queue>#include <utility> // pairusing namespace std;struct Node{        int data;        Node* left;        Node* right;};vector<Node*> lightFall(Node* root){        vector<Node*> result; // store the nodes on which the light will fall on        queue< pair<Node*, int> > que;        que.push( pair<Node*, int>(root, 0) ); // First, push the root node        int level = 0; // the level of the nodes        while(que.size()>0)        {                pair<Node*, int> frontPair = que.front();                que.pop();                if(level == frontPair.second) // only push back the first node of each level                {                        result.push_back(frontPair.first);                        level++;                }                if(frontPair.first->left)                        que.push( pair<Node*, int>( (frontPair.first)->left, frontPair.second+1) );                if(frontPair.first->right)                        que.push( pair<Node*, int>( (frontPair.first)->right, frontPair.second+1) );        }}


注意:first和second是pair 的两个member variable,而不是member function。

0 0
原创粉丝点击