LintCode 242. Convert Binary Tree to Linked Lists by Depth (BFS分层遍历)

  1. Convert Binary Tree to Linked Lists by Depth
    中文English
    Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you’ll have D linked lists).

Example
Example 1:

Input:
{1,2,3,4}
1
/
2 3
/
4
Output:
[
1->null,
2->3->null,
4->null
]
Example 2:

Input:
{1,#,2,3}
1

2
/
3
Output:
[
1->null,
2->null,
3->null
]

解法1:BFS分层遍历
代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param root the root of binary tree
     * @return a lists of linked list
     */
    vector<ListNode*> binaryTreeToLists(TreeNode* root) {
        if (!root) return vector<ListNode*>();
        queue<TreeNode *> q;
        vector<ListNode *> result;
        ListNode * listNode;
                    
        q.push(root);

        while(!q.empty()) {
            int n = q.size();
            ListNode * dummyHead = new ListNode(0);
            listNode = dummyHead;
            for (int i = 0; i < n; ++i) {
                TreeNode * treeNode = q.front();
                q.pop();
                
                listNode->next = new ListNode(treeNode->val);
                listNode = listNode->next;

                if (treeNode->left) {
                    q.push(treeNode->left);
                }
                if (treeNode->right) {
                    q.push(treeNode->right);
                }
            }

            listNode->next = NULL;

            result.push_back(dummyHead->next);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值