LintCode 70 二叉树的层次遍历 II

xiaoxiao2021-02-27  346

题目:levelOrderBottom


要求:

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

样例:

给出一棵二叉树 {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 按照从下往上的层次遍历为: [ [15,7], [9,20], [3] ]

算法要求:

解题思路:

直接倒着输出即可。

算法如下:

int getSize(TreeNode *root) { if (root == NULL) { return 1; } return getSize(root->left) + getSize(root->right); } vector<vector<int> > levelOrderBottom(TreeNode *root) { // write your code here vector<vector<int> > vec; if (root == NULL) { return vec; } int size = getSize(root) - 1; queue<TreeNode*> que; que.push(root); vector<int> *v = new vector<int>(); int n = 1; int i = 0; int j = 0; while (!que.empty() && j < size) { TreeNode *now = que.front(); que.pop(); i++; if (now) { v->push_back(now->val); j++; } if (i >= n) { i = 0; n *= 2; if (!v->empty()) { vec.push_back(*v); v = new vector<int>(); } } if (now) { que.push(now->left); que.push(now->right); } else{ que.push(NULL); que.push(NULL); } } if (!v->empty()) { vec.push_back(*v); } vector<vector<int> > vec2; size = vec.size(); for (int i = 0; i < size; i++) { vec2.push_back(vec[size - i - 1]); } return vec2; }
转载请注明原文地址: https://www.6miu.com/read-1536.html

最新回复(0)