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

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

#include <vector>
#include <queue>
#include <utility> // pair

using 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。

你可能感兴趣的:(Light is falling on a tree from left side you have to find all the nodes on which this light will fa)