2019年11月10日 星期日

Convert Binary Tree to Linked Lists by Depth


Convert Binary Tree to Linked Lists by Depth

  • Lintcode : 242 / Leetcode :
  • Level : Easy

Problem

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}
Output: [1->null,2->3->null,4->null]
Explanation: 
        1
       / \
      2   3
     /
    4
Example 2:

Input: {1,#,2,3}
Output: [1->null,2->null,3->null]
Explanation: 
    1
     \
      2
     /
    3

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n)
space: O(n)

Answer

/**
 * 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:
    vector<ListNode*> binaryTreeToLists(TreeNode* root) {
        // corner case 
        if (root == nullptr) return vector<ListNode*>();

        queue<TreeNode*> q;
        q.push(root);
        vector<ListNode*> ans;
        while (!q.empty()) {
            int s = q.size(); // level order
            ListNode* head = new ListNode(0);
            ListNode* dummy = head;
            for (int i = 0; i < s; i++) {
                TreeNode* node = q.front(); q.pop();
                head -> next = new ListNode(node -> val);
                if (node -> left) q.push(node -> left);
                if (node -> right) q.push(node -> right);
                head = head -> next;
            }
            ans.push_back(dummy -> next);
        }
        return ans;
    }
};
tags: BFS

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...