先序遍历
递归版
非递归版
中序遍历
递归版
非递归版
后序遍历
递归版
非递归版
层序遍历
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int> ans;
if (root == nullptr) return ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* front = q.front();
ans.push_back(front->val);
q.pop();
if (front->left != nullptr) q.push(front->left);
if (front->right != nullptr) q.push(front->right);
}
return ans;
}
};
树的层次遍历
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == nullptr) return ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> temp;
int len = q.size();
for (int i = 0; i < len; i++) {
TreeNode* front = q.front();
temp.push_back(front->val);
q.pop();
if (front->left != nullptr) q.push(front->left);
if (front->right != nullptr) q.push(front->right);
}
ans.push_back(temp);
}
return ans;
}
};