2019年11月7日 星期四

Binary Tree Level Order Traversal


Binary Tree Level Order Traversal

  • Lintcode : 69 / Leetcode : 102
  • Level : Easy

Problem

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Example
Example 1:

Input:{1,2,3}
Output:[[1],[2,3]]
Explanation:
  1
 / \
2   3
it will be serialized {1,2,3}
level order traversal
Example 2:

Input:{1,#,2,3}
Output:[[1],[2],[3]]
Explanation:
1
 \
  2
 /
3
it will be serialized {1,#,2,3}
level order traversal
Challenge
Challenge 1: Using only 1 queue to implement it.

Challenge 2: Use BFS algorithm to do it.

Notice
The first data is the root node, followed by the value of the left and right son nodes, and "#" indicates that there is no child node.
The number of nodes does not exceed 20.

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n) (n = tree nodes)
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;
 *     }
 * }
 */

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode * root) {
        vector<vector<int>> ans;
        if (root == nullptr) return ans;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            vector<int> res;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode * node = q.front(); q.pop();
                res.push_back(node -> val);
                if (node -> left != nullptr) {
                    q.push(node -> left);
                }
                if (node -> right != nullptr) {
                    q.push(node -> right);
                }
            }
            ans.push_back(res);
        }
        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 ...