zoukankan      html  css  js  c++  java
  • 面试题 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;
        }
    };
    
  • 相关阅读:
    8.10日报
    8.9日报
    8.8日报
    8.7日报
    《大道至简》读后感
    8.6日报
    8.5日报
    8.4日报
    8.3日报
    8.2日报
  • 原文地址:https://www.cnblogs.com/studywithallofyou/p/13631969.html
Copyright © 2011-2022 走看看