华为机试:完全二叉树非叶子部分后序遍历
题目来源
题目描述
题目解析
-
思路: 它是一个完全二叉树,所以我们用数组来存储它。而且数组的第0位不用,那么对于每一个数,它的左右子节点的索引分别是2 * i,2 * i + 1 然后我们递归: 一般二叉树的遍历流程: 检测当前节点是不是NULL,如果是,那么直接返回 否则: 处理左子树 处理右子树 打印当前值 那么,对于本题,我们不处理叶子节点就好啦: 检测当前节点是不是NULL,如果是,那么直接返回 检测当前节点是不是叶子节点,如果是,那么直接返回 否则: 处理左子树 处理右子树 打印当前值
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <map>
#include <random>
#include <ctime>
#include <iterator>
using namespace std;
class Solution{
bool isLeaf(std::vector<int> &nums, int i){
return (2 * i >= nums.size()) && (2 * i + 1 >= nums.size());
}
// 节点从1开始,索引0不存
void postOrder(std::vector<int> & num, int i){
// 当前节点超出索引
if(i >= num.size()){
return;
}
//当前节点是不是叶子节点(如果是,什么也不干)
if(isLeaf(num, i)){
return;
}
// 如果不是
// 处理左右节点
postOrder(num, 2 * i);
postOrder(num, 2 * i + 1);
// 打印当前值
printf("%d ", num[i]);
}
std::vector<int> split(std::string str){
std::vector<int> ans{
0};
int j = 0;
for (int i = 0; i < str.size(); ++i) {
if(str[i] == ){
ans.push_back(stoi(str.substr(j, i - j)));
j = i + 1;
}
}
return ans;
}
public:
void process(std::string str){
auto vec = split(str);
postOrder(vec, 1);
}
};
int main(){
std::string str = "1 2 3 4 5 6 7";
getline(std::cin, str);
Solution a;
a.process(str);
}
下一篇:
摆渡的士兵分析(一)以及代码实现
