程序员面试金典 - 面试题 04.03. 特定深度节点链表(BFS)

1. 题目

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

例:
输入:[1,2,3,4,5,null,7,8]

        1
       /  \ 
      2    3
     / \    \ 
    4   5    7
   /
  8

输出:[[1],[2,3],[4,5,7],[8]]

2. 解题

  • 层序,BFS遍历
class Solution {
public:
    vector<ListNode*> listOfDepth(TreeNode* tree) {
    	if(!tree)
    		return {};
    	queue<TreeNode*> q;
    	vector<ListNode*> ans;
    	q.push(tree);
    	int size;
    	TreeNode* tp;
    	ListNode* head, *cur;
    	bool hashead;
    	while(!q.empty())
    	{
    		size = q.size();
    		hashead = false;
    		while(size--)
    		{
    			tp = q.front();
    			q.pop();
    			if(!hashead)
    			{
    				head = new ListNode(tp->val);
    				cur = head;
    				hashead = true;
    			}
    			else
    			{
    				cur->next = new ListNode(tp->val);
    				cur = cur->next;
    			}
    			if(tp->left)
    				q.push(tp->left);
    			if(tp->right)
    				q.push(tp->right);
    		}
    		ans.push_back(head);
    	}
    	return ans;
    }
};

在这里插入图片描述

发布了748 篇原创文章 · 获赞 921 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105001378