LeetCode 107. 二叉树的层次遍历 II

题目链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

在第一个的基础上逆序一下

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrderBottom(TreeNode* root) {
13          vector<vector<int> > result;
14         if(root == nullptr) return result;
15         queue<TreeNode*> current, next;
16         vector<int> level; // elments in level level
17         current.push(root);
18         while (!current.empty()) {
19             while (!current.empty()) {
20                 TreeNode* node = current.front();
21                 current.pop();
22                 level.push_back(node->val);
23                 if (node->left != nullptr) next.push(node->left);
24                 if (node->right != nullptr) next.push(node->right);
25             }
26             result.push_back(level);
27             level.clear();
28             swap(next, current);
29         }
30         reverse(result.begin(), result.end());
31         return result;
32     }
33 };

 

posted @ 2019-11-12 12:03  wydxry  阅读(199)  评论(0编辑  收藏  举报
Live2D