算法练习:JZ32 从上往下打印二叉树
思路:使用队列层次遍历二叉树
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:vector<int> PrintFromTopToBottom(TreeNode* root) {vector<int> nums;queue<TreeNode*> q;TreeNode* current = NULL;// Step1.特殊情况处理if(root == NULL) return nums;// Step2.根结点入队q.push(root);// Step3.遍历二叉树while(q.empty() != true){// 将队列首结点取出,并将值放入nums中current = q.front();q.pop();nums.push_back(current->val);// 将左右结点放入队列,作为下一次处理的对象 if(current->left != NULL)q.push(current->left);if(current->right != NULL)q.push(current->right);}return nums;}
};
思路二:使用二维数组递归遍历二叉树
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:void recursion(TreeNode* root, vector<vector<int>> &nums, int depth){// Step0.特殊情况处理if(root){// Step1.将当前结点值放入numsif(nums.size() < depth+1)nums.push_back(vector<int>{});nums[depth].push_back(root->val);// Step2.递归左右子结点if(root->left) recursion(root->left, nums, depth+1);if(root->right) recursion(root->right, nums, depth+1);} }vector<int> PrintFromTopToBottom(TreeNode* root) {vector<int> results;// Step0.特殊情况处理if(root == NULL) return results;// Step1.递归遍历二叉树,将值按深度放入numsvector<vector<int>> nums; // 第一维表示二叉树的深度,第二维表示该深度的元素int depth = 0;recursion(root, nums, depth);// Step2.将输出nums的值放入一维数组中for(int i=0; i<nums.size(); i++)for(int j=0; j<nums[i].size(); j++)results.push_back(nums[i][j]);return results;}
};
运行时间:4ms 占用内存:548KB