本篇主要记录两个算法代码
中序非递归算法
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> s;
s.push(root);
while (!s.empty())
{
TreeNode* p = s.top();
if (p->left)
s.push(p->left);
else{
ans.push_back(p->val);
s.pop();
if (p->right)
s.push(p->right);
}
}
return ans;
}
};
层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == NULL) return ans;
int front = 0, rear = 0, last = 0;
vector<TreeNode*> q(100);
q[rear++] = root;
last = rear;
while (front != rear)
{
vector<int> vec;
while (front != last)
{
TreeNode* p = q[front++];
if (p->left) q[rear++] = p->left;
if (p->right) q[rear++] = p->right;
vec.push_back(p->val);
}
ans.push_back(vec);
last = rear;
}
return ans;
}