输出单层结点

来源:互联网 发布:tesla model s 知乎 编辑:程序博客网 时间:2024/05/01 11:27

Question

对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。
给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000。

Algorithm

1、首先知道什么时候换层
将A出队,并将A的子孩子入队,更新nlast=A最后入队的子孩子;
将A和last比较, 如果相同则换行,并更新last=nlast,如果 不相同,则continue
2、如何知道深度
换层的时候,记录当前层数

Code

/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*//*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};*/class TreeLevel {public:    ListNode* getTreeLevel(TreeNode* root, int dep) {        // write code here        queue<TreeNode*> s;        ListNode* res=new ListNode(-1);        ListNode* p=res;        TreeNode* last=root;        TreeNode* nlast=NULL;        s.push(root);        int count=1;        while(!s.empty()){            TreeNode* tmp=s.front();            s.pop();            if(dep == count){                p->next=new ListNode(tmp->val);                p=p->next;            }            if(tmp->left!=NULL){                s.push(tmp->left);                nlast=tmp->left;            }            if(tmp->right!=NULL){                s.push(tmp->right);                nlast=tmp->right;            }            if(tmp->val == last->val){                if(count == dep)                    return res->next;                last=nlast;                count++;            }        }        return res->next;    }};
0 0
原创粉丝点击