首页 > 代码库 > 【Lintcode】069.Binary Tree Level Order Traversal

【Lintcode】069.Binary Tree Level Order Traversal

题目:

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]
]

题解:

  三种处理方法:queue + queue; queue + ‘dummy’;queue

Solution 1 ()

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) {
        vector<vector<int>> res;
        if (root == NULL) {
            return res;
        }
        queue<TreeNode*> queue;
        vector<int> levelNode;
        
        queue.push(root);
        queue.push(nullptr);
        while(!queue.empty()) {
            TreeNode *node = queue.front();
            queue.pop();
            if (node == nullptr) {
                res.push_back(levelNode);
                levelNode.resize(0);
                if (q.size() > 0) {
                    q.push(nullptr);
                }
            } else { 
                levelNode.push_back(root->val);
                if (node->left != nullptr) {
                    queue.push(node->left);
                }
                if (node->right != nullptr) {
                    queue.push(node->right);
                }
            }
        }
 
        return res;
    }
};

Solution 2 ()

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

  程序中的size是必要的,因为在for循环中queue是不断变化的,那么queue.size()也是不断变化的,这就违背了我们的原则,这个size就是该层所有的非空node的个数,取完之后就要压入result中,读取下一层的节点

【Lintcode】069.Binary Tree Level Order Traversal