LeetCode: 107. Binary Tree Level Order Traversal II

LeetCode: 107. Binary Tree Level Order Traversal II

题目描述

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

题目大意: 自底向上层次遍历二叉树。

解题思路

LeetCode: 102. Binary Tree Level Order Traversal 题解 的结果反转即可。

AC 代码

/** * 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 {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> leverOrderSequence;         // 保存层次遍历序列
        vector<int>         curLevel;                   // 保存当前层的序列

        queue<TreeNode*> que;   // BFS 队列
        que.push(root);         // 将根节点加入 BFS 对列
        que.push(nullptr);      // 用 nullptr 来隔开每一层的元素


        while(!que.empty())
        {
            TreeNode* curNode = que.front();
            que.pop();

            if(curNode == nullptr && curLevel.empty())
            {
                continue;
            }
            else if(curNode == nullptr && !curLevel.empty())
            {
                que.push(nullptr);
                leverOrderSequence.push_back(curLevel);
                curLevel.clear();
            }
            else
            {
                curLevel.push_back(curNode->val);
                if(curNode->left != nullptr) que.push(curNode->left);
                if(curNode->right != nullptr) que.push(curNode->right);
            }
        }

        // 翻转结果
        reverse(leverOrderSequence.begin(), leverOrderSequence.end());
        return leverOrderSequence;
    }
};
全部评论

相关推荐

M_bao:换个排版吧哥们,看着费劲
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务