Binary Tree Level Order Traversal

Description

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

Example
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

Challenge Challenge 1: Using only 1 queue to implement it.

  • we are here

Challenge 2: Use DFS algorithm to do it.

  • DFS and record the depth

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
public:
    vector<vector<int>> levelOrder(TreeNode *root) {
        // write your code here
        vector<vector<int>> result;
        if (!root) {
            return result;
        }
        int order = 0;
        int count = 1;
        // stardard Breadth-first-search
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode* cur = q.front();
            q.pop();
            count--;
            if (order+1 > result.size()) {
                result.push_back(vector<int>(1, cur->val));
            } else {
                result[order].push_back(cur->val);
            }
            if (cur->left) {
                q.push(cur->left);
            }
            if (cur->right) {
                q.push(cur->right);
            }
            if (count < 1) {
                ++order;
                count = q.size();
            }
        }
        return result;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""