每天一道Code 面试题 04.03. 特定深度节点链表

在这里插入图片描述
代码思路
简单层次遍历。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<ListNode*> listOfDepth(TreeNode* tree) {
    
    
        ListNode *dummy = new ListNode(-1);
        ListNode *head = dummy;
        vector<ListNode*> v;
        queue<TreeNode*> q;
        q.push(tree);
        while(!q.empty()){
    
    
            int len = q.size(); //判断一层有多少结点,把这些结点都弹出
            while(len--){
    
    
                TreeNode *tmp = q.front();
                q.pop();
                if(tmp->left) q.push(tmp->left);    //子节点入队,不会影响len
                if(tmp->right) q.push(tmp->right);
                head->next = new ListNode(tmp->val);    //链接
                head=head->next;
            }
            v.push_back(dummy->next);               //这一层链接完入vector
            head=dummy;
        }
        return v;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41746268/article/details/108267338