美文网首页
C++-Binary Tree Level Order Trav

C++-Binary Tree Level Order Trav

作者: FlyElephant | 来源:发表于2018-08-09 11:09 被阅读9次

    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).

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

        3
       / \
      9  20
        /  \
       15   7
    

    return its bottom-up level order traversal as:

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

    二叉树的层次遍历,不过需要保持每一层的数据,可以通过vector配合队列实现,实现:

    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> vvi;
            if (root == NULL) {
                return vvi;
            }
            queue<TreeNode *> queue;
            queue.push(root);
            while (!queue.empty()) {
                vector<int> vi;
                int size = (int)queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode *node = queue.front();
                    queue.pop();
                    if (node->left != NULL) {
                        queue.push(node->left);
                    }
                    if (node->right != NULL) {
                        queue.push(node->right);
                    }
                    vi.push_back(node->val);
                }
                vvi.push_back(vi);
            }
            reverse(vvi.begin(), vvi.end());
            return vvi;
        }
    };
    

    相关文章

      网友评论

          本文标题:C++-Binary Tree Level Order Trav

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