美文网首页
LintCode 70. Binary Tree Level O

LintCode 70. Binary Tree Level O

作者: Andiedie | 来源:发表于2017-11-10 15:40 被阅读0次

    原题

    LintCode 70. Binary Tree Level Order Traversal II

    Description

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

    Example

    Given binary tree {3,9,20,#,#,15,7},

        3
       / \
      9  20
        /  \
       15   7
    

    return its bottom-up level order traversal as:

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

    代码

    /**
     * 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:
        /*
        * @param root: A tree
        * @return: buttom-up level order a list of lists of integer
        */
        vector<vector<int>> levelOrderBottom(TreeNode * root) {
            // write your code here
            vector<vector<int>> res;
            if (root == NULL) return res;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty()) {
                int size = q.size();
                vector<int> level;
                for (int i = 0; i < size; i++) {
                    TreeNode *cur = q.front();
                    q.pop();
                    level.push_back(cur->val);
                    if (cur->left) q.push(cur->left);
                    if (cur->right) q.push(cur->right);
                }
                res.insert(res.begin(), level);
            }
            return res;
        }
    };
    

    相关文章

      网友评论

          本文标题:LintCode 70. Binary Tree Level O

          本文链接:https://www.haomeiwen.com/subject/noibmxtx.html