当前位置: 代码迷 >> 综合 >> 42 二叉树的层次遍历 II
  详细解决方案

42 二叉树的层次遍历 II

热度:68   发布时间:2024-02-22 19:02:22.0

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

 

例如:

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

    3

   / \

  9  20

     /  \

   15   7

返回其自底向上的层次遍历为:

[

  [15,7],

  [9,20],

  [3]

]

程序输出为:

15 7 9 20 3

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

 

  相关解决方案