102. Binary Tree Level Order Traversal

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

For example:
Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Thoughts:

  1. PreOrder Traversal + Add a "depth" variable to keep track of what level curNode should be inserted into
  2. Solve using Queue

Code 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    vector<vector<int>>answer;
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        levelOrderHelper(root,0);
        return answer;
    }

    void levelOrderHelper(TreeNode* cur, int depth){
        if(!cur) return;

        if(answer.size()==depth)answer.push_back(vector<int>());
        answer[depth].push_back(cur->val);
        levelOrderHelper(cur-> left, depth + 1);
        levelOrderHelper(cur-> right, depth + 1);
    }
};

Code 2

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    vector<vector<int>> answer;
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
       queue <TreeNode*> q;
       if(root) q.push(root);
        while(!q.empty()){
            int len = q.size();
            vector<int> level;
            for(int i = 0; i < len; i ++){
                TreeNode* cur = q.front();
                level.push_back(cur->val);
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
                q.pop();
            }
            answer.push_back(level);
        }
        return answer;
    }
};

Code 2: checking null at the current node

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    vector<vector<int>> answer;
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
       queue <TreeNode*> q;
         q.push(root);
        while(!q.empty()){
            int len = q.size();
            vector<int> level;
            for(int i = 0; i < len; i ++){
                TreeNode* cur = q.front(); q.pop();
                if (!cur) continue;
                level.push_back(cur->val);
                q.push(cur->left);
                q.push(cur->right);
            }
            if (!level.empty()) answer.push_back(level);
        }
        return answer;
    }
};

results matching ""

    No results matching ""