面试题 04.03. 特定深度节点链表

https://leetcode-cn.com/problems/list-of-depth-lcci/

这道题比较简单,就是遍历树,广度优先,一层层的遍历,唯一需要注意的是,如何定义到了第几层,做法就是在每一层结束,下一层开始,加入一个标识符。

/**
 * 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) {
        vector<ListNode*> alist;
        if (tree != NULL)
        {
            queue<TreeNode*> nodequeue;
            ListNode* plnode = NULL;
            nodequeue.push(tree);
            nodequeue.push(NULL);
            TreeNode * tnode = NULL;
            int tlevel = 0;
            while (!nodequeue.empty())
            {
                tnode = nodequeue.front();
                nodequeue.pop();
                if (tnode == NULL)
                {
                    tlevel++;
                    if (nodequeue.empty())
                    {
                        break;
                    }
                    plnode = NULL;
                    nodequeue.push(NULL);
                    continue;
                }
                else
                {
                    if (plnode == NULL)
                    {
                        plnode = new ListNode(0);
                        plnode->val = tnode->val;
                        alist.emplace_back(plnode);
                    }
                    else
                    {
                        plnode->next = new ListNode(0);
                        plnode = plnode->next;
                        plnode->val = tnode->val;
                    }
                }
                if (tnode->left != NULL)
                {
                    nodequeue.push(tnode->left);
                }
                if (tnode->right != NULL)
                {
                    nodequeue.push(tnode->right);
                }
            }
        }
        return alist;
    }
};
posted @ 2020-09-08 13:22  秋来叶黄  阅读(148)  评论(0编辑  收藏  举报