Abstract

做了一道题Tree : Top View。下面是解题报告。

Top View

什么是Top View呢?
在二叉树的父节点,从下看:你能看到的结点的集合即是Top View。
如下图:结点7和13被8挡住了,所以看不到。只能看到 结点4,8,16,20。
Tree : Top View
怎么确定结点是否被挡在了呢?如上图的po。我是这样定义的:对与一个结点来说:它的左结点位置为该节点位置减一,右结点的位置为该结点位置加一。然后把根节点的位置设为0。
这样:对树进行遍历:这样就能把树的所有结点的位置确定下来。
这里我选择的是层序遍历:因为其他三种遍历:左数的遍历顺序一定会先于右树。但是层序遍历是一层一层遍历。就好像站队一样,其他三种遍历是直接插入队伍去,这是不对的。



Code:

void topView(Node * root) {
        if(root == nullptr)
            return;
        queue<pair<Node*,int>> q;
        map<int,Node*> top;
        q.push(make_pair(root,0));
        top[0]=root;
        while(!q.empty()){
            auto temp = q.front();
            q.pop();
            if(temp.first->left){
                q.push(make_pair(temp.first->left,temp.second-1));
                if(top.find(temp.second-1)==top.end())
                    top[temp.second-1]=temp.first->left;
            }
            if(temp.first->right){
                q.push(make_pair(temp.first->right,temp.second+1));
                if(top.find(temp.second+1)==top.end())
                    top[temp.second+1]=temp.first->right;
            }
        }
        for(auto x:top)
            cout<<x.second->data<<" ";
    }




reference
geeksforgeeks

相关文章: